Go core
Browse topics

Formatting and parsing time

Version
1.27
Review
Draft

Summary#

A Go layout shows how the reference time Mon Jan 2 15:04:05 MST 2006 should look. Format writes a time in that shape and Parse reads it. Parse assumes UTC when the input has no zone information.

Syntax#

go
text := moment.Format(time.RFC3339)
parsed, err := time.Parse(time.RFC3339, text)
local, err := time.ParseInLocation("2006-01-02 15:04", localText, location)

Example#

go
package main

import (
	"fmt"
	"time"
)

func main() {
	moment := time.Date(2026, time.March, 5, 14, 7, 9, 0, time.UTC)
	fmt.Println(moment.Format(time.RFC3339))
	fmt.Println(moment.Format("02/01/2006 15:04"))
	fmt.Println(moment.Format("Mon, Jan 2 at 3:04 PM"))
	fmt.Println(moment.Format("YYYY-MM-DD")) // not a Go layout

	hanoi := time.FixedZone("ICT", 7*60*60)
	local, err := time.ParseInLocation(time.DateTime, "2026-03-05 14:07:09", hanoi)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(local.Format(time.RFC3339))
	fmt.Println(local.UTC().Format(time.TimeOnly))

	_, err = time.Parse(time.DateOnly, "2026-02-30")
	fmt.Println(err)
}

Expected output#

Text
2026-03-05T14:07:09Z
05/03/2026 14:07
Thu, Mar 5 at 2:07 PM
YYYY-MM-DD
2026-03-05T14:07:09+07:00
07:07:09
parsing time "2026-02-30": day out of range

Common mistakes#

Patterns such as YYYY-MM-DD are printed literally. Use the reference values 2006 for the year, 01 for the month and 02 for the day. Use 15 for a 24-hour clock and 3 or 03 for a 12-hour clock. FixedZone applies the same offset year-round.

Version applicability#

Reference layouts, Format, Parse and FixedZone date back to Go 1.0. ParseInLocation requires Go 1.1. The complete example requires Go 1.20 for DateTime, DateOnly and TimeOnly. Use the layout strings on earlier versions.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0