Time and date

suggest change

The Go time package provides functionality for handling time and date.

Major types in the package:

Get current time and date

now := time.Now()

Construct a time and date at a given moment in time

t := time.Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

loc is the time zone. Use time.UTC for UTC. A nil loc is also treated as UTC.

Compare two times for equality

areEqual := t1.Equal(t2)

Add duration to time

newTime := now.Add(5 * time.Second + time.Millisecond * 100)

Time values are immutable. Add returns a new value.

Subtract duration from time

newTime := now.Add(-6 * time.Second)

To subtract 6 seconds we add -6 seconds.

Add years, months, days to time

A Duration can be longer than a day, but it is a fixed number of nanoseconds. Calendar years, months, and days are not fixed lengths.

To advance a time by calendar years, months, or days, use:

years := 2
months := 3
days := 13
t2 := t.AddDate(years, months, days)

Convert time to Unix representation of time

For interoperability with existing code you often need to use Unix time, which is defined as number of seconds since January 1, 1970 UTC.

unixTime := t.Unix()

Get year, month and day from time

year, month, day := t.Date()

Format time

Parse time

Format time like strftime

Compare time and date

Feedback about page:

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



Table Of Contents