Start date and time format

Learn how to format dates in Go using format constants or custom formats

In Go, you can usetime.Now(),bytimepackage.

t := time.Now()

This will print the system local time. Need UTC? Attach.UTC():

Time can be usedtime.Format()method:

t := time.Now().UTC()

Do you need a time stamp?

t := time.Now().Unix()

Use custom format

An example of formatting using a custom format is as follows:

fmt.Println(t.Format("2006-01-02 15:04:05"))

that2006-01-02 15:04:05The string looks strange, doesn't it? It's not like 2006! But it will print (at the time of writing)2017-01-16 12:53:51

If you are not familiar with Go, this soundsvery muchStrange.

The explanation is as follows: Go's time format is unique and different from other languages. Go uses the reference date instead of using the traditional format to print the date,20060102150405This seems meaningless, but there is actually a reason, because1 2 3 4 5 6In Posixdatecommand:

Mon Jan 2 15:04:05 -0700 MST 2006
0   1   2  3  4  5              6

The time zone in the middle should be7(Not sure why they didn’t chooseMon Jan 2 03:04:05 -0600 MST 2007, Incidentally)

Interesting historical reference:https://github.com/golang/go/issues/444

Use format constants

Go providestimePack some convenient constants in common 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"
)

You can use them like this:

t := time.Now()
fmt.Println(t.Format(time.ANSIC))

More tutorials: