block by joyrexus a56717634a672dcdfd48

time in go

Working with time in Go is pretty straightforward.

Times

Get the current local time:

now := time.Now()                                   // 02 Apr 15 14:03

Construct a time with Date(y, m, d, h, m, s, ns, loc):

y := 2009
m := time.November
d := 10
h := 23
m := 0
s := 0
t := time.Date(y, m, d, h, m, s, 0, time.UTC)       // 10 Nov 09 23:00

Durations

Given a Time, you can add a Duration.

To convert an integer number of time units (seconds, minutes, etc.) to a Duration, just multiply:

now := time.Now()                                   // 02 Apr 15 14:03

mins := 10
later := now.Add(time.Duration(mins) * time.Minute) // 02 Apr 15 14:13

You can also use AddDate(y, m, d) to add a given number of years, months, days:

y := 2
m := 2
d := 2

later := now.AddDate(y, m, d)                       // 04 Jun 17 14:13

Formatting

Various formatting options are pre-defined:

fmt.Println(now.Format(time.RFC822))                // 02 Apr 15 14:03 CDT
fmt.Println(now.Format(time.Kitchen))               // 2:13PM

You can also define your own format with an example layout:

const layout = "Jan 2, 2006 at 3:04pm"
fmt.Println(now.Format(layout))                     // Apr 2, 2015 at 2:13pm

Parsing

You also use layouts for parsing strings representing times:

const shortForm = "2006-01-02"
loc, _ := time.LoadLocation("America/Chicago")

t, _ := time.ParseInLocation(shortForm, "2015-01-19", loc)

The time t is now 2015-01-19 00:00:00 -0600 CST.

Encoding/Decoding

See codec.go example.

codec.go

time.go