Format time

suggest change

Most languages inherited time formatting method from strftime function C library which uses somewhat cryptic format strings like %Y-%m-%d.

Go designers came up with arguably more intuitive way of time parsing and formatting where you show a template of how you want the result to look like:

	t := time.Date(2017, 9, 4, 3, 38, 45, 0, time.UTC)
	fmt.Println(t.Format("2006-01-02 15:04:05.000 MST"))
	fmt.Println(t.Format("2006-01-2 15pm"))
	fmt.Println(t.Format("Jan 06 Mon 01 2"))
	fmt.Println(t.Format("January 2006 Mon 2"))
	fmt.Println(t.Format("Month: Jan '1', '01', _2"))
2017-09-04 03:38:45.000 UTC
2017-09-4 03am
Sep 17 Mon 09 4
September 2017 Mon 4
Month: Sep '9', '09',  4

Formatting string is an arbitrary string with some parts being replaced by the data from time.Time value:

template meaning
2006, 06 4- or 2-digit year
1, 01 month, 1–12 (01 is zero-padded)
2, 02, _2 day, 1–31 (02 is zero-padded, _2 is space-padded)
15 hour, 00–23
4, 04 minute
5, 05 second
MST time zone as a string
-0700 time zone as numeric offset
Jan, January short or long month name
Mon, Monday short or long day name

The layout numbers come from the reference time Mon Jan 2 15:04:05 MST 2006: 1 is the month (January), 2 is the day. Prefix a 0 to zero-pad (01 is 09 for September) or _ to space-pad (_2 is 4 for the 4th). A lone 6 is not a year; use 06 or 2006.

Package time also defines constants for some well-known formats for date/time formatting e.g. time.RFC822 is date format defined in RFC 822 which is date format in e-mail messages.

Here’s a full list of pre-defined formats:

const (
        ANSIC       = "Mon Jan _2 15:04:05 2006"
        UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
        RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
        RFC822      = "02 Jan 06 15:04 MST"
        RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
        RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
        RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
        RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
        RFC3339     = "2006-01-02T15:04:05Z07:00"
        RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
        Kitchen     = "3:04PM"
        // Handy time stamps.
        Stamp      = "Jan _2 15:04:05"
        StampMilli = "Jan _2 15:04:05.000"
        StampMicro = "Jan _2 15:04:05.000000"
        StampNano  = "Jan _2 15:04:05.000000000"
)

What if you prefer strftime style of formatting time? That’s available too.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents