~/Golang Datetime Format Handling

Sep 16, 2021


Dealing with datetime in Go relies on the time package. Go uses a unique reference time, Mon Jan 2 15:04:05 MST 2006, for parsing and formatting times.

Parsing a datetime string:

1
2
3
4
5
layout := "2006-01-02 15:04:05"
t, err := time.Parse(layout, "2021-09-15 14:23:00")
if err != nil {
    // handle error
}

Formatting a time.Time object:

1
2
t := time.Now()
s := t.Format("2006-01-02 15:04:05")

For time zones, use time.LoadLocation:

1
2
loc, _ := time.LoadLocation("America/New_York")
t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2021-09-15 14:23:00", loc)

Always remember the layout must match the input or output format exactly. For a complete reference, use the official Go time documentation.

Tags: [golang] [datetime] [time]