5.5. Date and Time

Basics

Time is represented with the time.Time struct.

The output in the examples below is generated by the Go playground . The Go playground uses a static time to achieve optimal caching performance.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package main

import (
	"fmt"
	"time"
)

func main() {
	time := time.Now()
	fmt.Println(time)
}
Output:
2009-11-10 23:00:00 +0000 UTC m=+0.000000001

Parsing

To parse a string to time.Time we use time.Parse . Other programming languages often use “format strings” that look something like: yyyy-MM-dd HH:mm:ss. Go does things differently and uses a reference time.

Jan 2 15:04:05 2006 MST

An easy way to remember this value is that it holds, when presented in this order, the values (lined up with the elements above):

 1  2  3  4  5   6  -7

Every layout string is a representation of this time stamp. If you want to format a date differently, you must rewrite the above date.

Example:

Mon Jan 2 15:04:05 MST 2006
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
	"fmt"
	"log"
	"time"
)

func main() {
	t, err := time.Parse("Mon Jan 2 15:04:05 MST 2006", "Thu Feb 25 11:06:39 PST 2021")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(t)
	fmt.Println(t.Weekday())
}
Output:
2021-02-25 11:06:39 +0000 PST
Thursday

Comparing dates

Dates can be compared with time.Before and time.After

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import (
	"fmt"
	"time"
)

func main() {
	year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
	year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)

	isYear3000AfterYear2000 := year3000.After(year2000) // True
	isYear2000AfterYear3000 := year2000.After(year3000) // False

	fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)
	fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)

}
Output:
year3000.After(year2000) = true
year2000.After(year3000) = false

Duration

A time.Duration represents the time between two instants.

To get a duration we can subtract two dates:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import (
	"fmt"
	"time"
)

func expensiveCall() {
	time.Sleep(10 * time.Second)
}

func main() {
	t0 := time.Now()
	expensiveCall()
	t1 := time.Now()
	duration := t1.Sub(t0)
	fmt.Printf("The call took %v to run.\n", duration)
}
Output:
The call took 10s to run.