Golang Time Format Example

Go (Golang) supports time formatting out of the standard library. It’s possible to specify a pattern-like format when converting a time.Time to a string value. It’s possible to use the following method: time.Format

func (t Time) Format(layout string) string

Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be Mon Jan 2 15:04:05 -0700 MST 2006 would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.

Format uses a layout defined as a default date 2 Jan 2006 which will be used to format the time, let’s see a couple of examples to better understand how this works.

Golang Time Format YYYY-MM-DD

Here’s a typical scenario, where we want to format a time.Time instance into a standard string in the YYYY-MM-DD format.

package main

import "time"
import "fmt"

func main() {
  now := time.Now()
  fmt.Println(now.Format("2006-02-01"))
}

which will result in

2009-10-11

Bear in mind that if you run this on play.golang.org the sandbox has been seeded with a static time value (2009-10-11) so you might see always the same date - try running these example on your machine

Golang Time Formatting Standards

In the Go (Golang) standard library we have also a bunch of useful constants used as layouts for formatting time, you can find them in the time package. Standard

Based on the above formats we can easily use any of those constants to format a time value as we prefer. Let’s see an example

package main

import "time"
import "fmt"

func main() {
  now := time.Now()
  fmt.Println(now.Format(time.RFC822))
  fmt.Println(now.Format(time.Kitchen))
  fmt.Println(now.Format(time.UnixDate))
}

Which results in the following

10 Nov 09 23:00 UTC
11:00PM
Tue Nov 10 23:00:00 UTC 2009
Join the Golang Developers Community on Golang Cafe