Go Time Parsing & Formatting Gotchas

Coming from other languages (Python's %Y-%m-%d or Java's yyyy-MM-dd), Go's time formatting approach can be baffling. Instead of codes, Go uses a specific Reference Time.

The Magic Date

Mon Jan 2 15:04:05 MST 2006

01/02 03:04:05PM '06 -0700

To format a date, you write how this specific date would look.

  • Month: 1 (01, Jan)
  • Day: 2 (02, _2)
  • Hour: 3 (15, 03)
  • Minute: 4 (04)
  • Second: 5 (05)
  • Year: 6 (2006, 06)
  • Zone: 7 (-07, MST)

Common Gotchas

1. Using random numbers

Go
// ❌ Wrong: Thinking it works like strftime
layout := "2024-12-25" // These are just random numbers!

// ✅ Correct: Use the reference date values
layout := "2006-01-02" // Year-Month-Day

2. Month vs Hour confusion

Go
// ❌ Wrong: Using 03 for month (03 = hour in 12h format)
layout := "2006-03-02"

// ✅ Correct: 01 is month, 02 is day
layout := "2006-01-02"

3. 12-hour vs 24-hour time

Go
// 15 = 24-hour format (15:04:05)
// 03 = 12-hour format (3:04:05 PM)

layout24 := "15:04:05"      // 14:30:00
layout12 := "03:04:05 PM"   // 02:30:00 PM

Common Layouts

Go
import "time"

// Predefined layouts in the time package
time.RFC3339     // "2006-01-02T15:04:05Z07:00"
time.RFC1123     // "Mon, 02 Jan 2006 15:04:05 MST"
time.Kitchen     // "3:04PM"
time.DateOnly    // "2006-01-02"  (Go 1.20+)
time.TimeOnly    // "15:04:05"    (Go 1.20+)

// Custom layouts
"2006-01-02"                    // ISO date
"01/02/2006"                    // US date
"02-Jan-2006"                   // European with month name
"2006-01-02 15:04:05"           // DateTime
"Mon Jan _2 15:04:05 2006"      // Unix date

FAQ

Why does Go use 2006-01-02 for formatting?

Go uses a specific reference time: Mon Jan 2 15:04:05 MST 2006. The values 1, 2, 3, 4, 5, 6, 7 correspond to Month, Day, Hour, Minute, Second, Year, Timezone.

How do I parse a date string in Go?

Use time.Parse(layout, value). The layout must describe how the reference time would look in that format.

Why am I getting parsing errors?

The most common reason is a mismatch between the layout and the input string, or using the wrong numbers in the layout (e.g., using 04 for month instead of 01).