Go by Example: Time Parsing
Parsing time strings converts them into `time.Time` objects. This example demonstrates `time.Parse` and handling errors with different layouts.
Code
package main
import (
"fmt"
"time"
)
func main() {
p := fmt.Println
// 1. Basic Parsing (RFC3339)
// Parse returns a time.Time and an error.
t1, err := time.Parse(time.RFC3339, "2023-11-01T22:08:41+00:00")
if err != nil {
panic(err)
}
p("Parsed RFC3339:", t1)
// 2. Custom Layout Parsing
// The layout string must match the input format exactly.
layout := "2006-01-02 3:04PM"
str := "2023-10-31 8:00PM"
t2, err := time.Parse(layout, str)
if err != nil {
panic(err)
}
p("Parsed Custom:", t2)
// 3. ParseInLocation (Handling Timezones)
// time.Parse usually returns time in UTC (if no offset is present).
// Use ParseInLocation to interpret time in a specific zone.
loc, _ := time.LoadLocation("America/New_York")
t3, _ := time.ParseInLocation("2006-01-02", "2023-12-25", loc)
p("Parsed in NY:", t3)
// 4. Handling Errors
_, err = time.Parse(time.RFC3339, "invalid-time")
if err != nil {
p("Parse Error:", err)
}
}
Explanation
Parsing time in Go is the inverse operation of formatting, utilizing the same reference time layout system to interpret string representations of dates and times into native time.Time objects. The time.Parse function takes a layout string and an input string, attempting to match the input against the template; strict adherence to the layout is enforced, meaning that any deviation in separators, spacing, or component order will result in a parsing error. This strictness ensures data integrity but requires developers to be intimately familiar with the exact format of their input data, particularly when dealing with non-standard or legacy date strings.
A critical nuance in parsing is timezone handling: time.Parse interprets the input as UTC unless a timezone offset is explicitly present in the string. To parse a time string that lacks offset information but is known to represent a specific local time (e.g., "2023-01-01 12:00"), developers must use time.ParseInLocation, which accepts a *time.Location argument. This function correctly associates the parsed time with the specified timezone, handling daylight saving time transitions and offset calculations accurately, which is essential for building robust applications that operate across multiple geographic regions.
- Strictness: Layout must match input exactly.
- UTC Default:
time.Parsedefaults to UTC if no offset is found. - Locations: Use
time.ParseInLocationfor local times. - Errors: Always check the returned error object.

