Go: Format a time or date

To format a date use the Format method:

func (t Time) Format(layout string) string

To parse a date string use the time.Parse function:

func Parse(layout, value string) (Time, error)

The layout parameter describes the format of a time value. It should be the magical reference date

Mon Jan 2 15:04:05 MST 2006

formatted the same way as the value is expected to be formatted.

Example: To parse "2017-08-31" we use the layout string "2006-01-02" since that is the yyyy-mm-dd formatting of the magical reference date.

input := "2017-08-31"
layout := "2006-01-02"
t, _ := time.Parse(layout, input)
fmt.Println(t)                       // 2017-08-31 00:00:00 +0000 UTC
fmt.Println(t.Format("02-Jan-2006")) // 31-Aug-2017

What's magical about Mon Jan 2 15:04:05 MST 2006? By formatting this date a bit differently…

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

…we see that no two fields are the same. This means that for this particular date, each field can be identified unambigously regardless of the formatting.

Common layouts

Go layout Java notation C notation Notes
2006-01-02 yyyy-MM-dd %F ISO 8601
20060102 yyyyMMdd %Y%m%d ISO 8601
January 02, 2006 MMMM dd, yyyy %B %d, %Y
02 January 2006 dd MMMM yyyy %d %B %Y
02-Jan-2006 dd-MMM-yyyy %d-%b-%Y
01/02/06 MM/dd/yy %D US
01/02/2006 MM/dd/yyyy %m/%d/%Y US
010206 MMddyy %m%d%y US
Jan-02-06 MMM-dd-yy %b-%d-%y US
Jan-02-2006 MMM-dd-yyyy %b-%d-%Y US
06 yy %y
Mon EEE %a
Monday EEEE %A
Jan-06 MMM-yy %b-%y

Time

Go layout Java notation C notation Notes
15:04 HH:mm %R
15:04:05 HH:mm:ss %T ISO 8601
3:04 PM K:mm a %l:%M %p US
03:04:05 PM KK:mm:ss a %r US

Date and time

Go layout Java notation C notation Notes
2006-01-02T15:04:05 yyyy-MM-dd'T'HH:mm:ss %FT%T ISO 8601
2006-01-02T15:04:05-0700 yyyy-MM-dd'T'HH:mm:ssZ %FT%T%z ISO 8601
2 Jan 2006 15:04:05 d MMM yyyy HH:mm:ss %e %b %Y %T
2 Jan 2006 15:04 d MMM yyyy HH:mm %e %b %Y %R
Mon, 2 Jan 2006 15:04:05 MST EEE, d MMM yyyy HH:mm:ss z %a, %e %b %Y %T %Z RFC 1123
RFC 822

More formats

If none of the above fits your need, you can give It's Go time! a try. It allows you to compose your own custom Go time layout string.

Corner cases

Here are some corner cases not handled by the time package.

Comments

Be the first to comment!