Reference Layout Controls Time Formatting

Format timestamps with Go's reference layout: the fixed template 2006-01-02 15:04:05 encodes each element, and Parse reuses the same layout in reverse.

GoData Integrity

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"time"
)

func main() {
	ts := time.Date(2026, 11, 18, 14, 5, 9, 0, time.UTC)

	// Go has no %Y-%m-%d style placeholders: the fixed reference time 01/02 03:04:05PM '06 is the template
	fmt.Println(ts.Format(time.RFC3339))
	fmt.Println(ts.Format("2006-01-02 15:04:05"))
	fmt.Println(ts.Format("Jan 2, 2006 3:04PM"))

	// Mnemonic: 1=month, 2=day, 3=hour, 4=minute, 5=second, 6=year, and 7 is the timezone
	fmt.Println(ts.Format("Monday, 02 Jan 2006"))

	// Parsing reuses the same reference layout in reverse
	parsed, err := time.Parse("2006-01-02 15:04", "2026-11-18 09:30")
	if err != nil {
		panic(err)
	}
	fmt.Println("parsed:", parsed.Format(time.Kitchen))
}

Inside the snippet

Count the function main as the entire surface area of Reference Layout Controls Time Formatting.

Nothing continues past an unchecked error — 1 if err != nil branch, each ending in panic(err).

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.
  • Adapting this to library code usually means replacing the panic(err) calls with error returns the caller can branch on.

Putting it to use

The run prints labeled lines — parsed: — when the file runs.

Core lines

if err != nil {
panic(err)
}

Interactive Tools for This Topic

FAQ

How should callers handle failures?
By terminating the run: `panic(err)` fires at each of the 1 check, so callers see failures only as a stopped program.
What does Reference Layout Controls Time Formatting print when run?
The script runs standalone; its 1 labeled outputs include `parsed:`.