How to get the current time in Go

Getting the current date and time in Go is easily achieved through the time package in the standard library

It is often necessary to retrieve the current date and time usually for the purpose of adding a timestamp to an event such as the creation of a resource. This task can be achieved easily through the Now() method from the built-in time package:

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println(time.Now())
}

This prints an output similar to what is shown below:

Output
2021-05-25 23:10:35.2207995 +0100 WAT m=+0.000110401

If you want a timestamp reflecting the number of seconds elapsed since January 1, 1970 00:00:00 UTC, use time.Now().Unix() or time.Now().UnixNano() for nanoseconds. If you’re looking for the equivalent of JavaScript’s Date.now() method in Go (milliseconds since January 1, 1970), divide the value of time.Now().UTC().UnixNano() by 1e6 (1,000,000).

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println(time.Now().Unix()) // 1621981229
	fmt.Println(time.Now().UnixNano()) // 1621981229584665200
	fmt.Println(time.Now().UTC().UnixNano() / 1e6) // 1621981229584
}

Thanks for reading, and happy coding!