Epoch and Date Time Conversion in Go

Go or often referred as Golang is well known statically typed, compiled programming language developed by Google. It is similar to C with features such as memory safety, garbage collection, structural typing and CSP-style concurrency. Go has time package that used to deal with dates and times. So with Go, we can easily handle epoch or Unix timestamp conversion into human readable dates or can convert human readable dates to Unix timestamp.

Here we will explain Go language functions to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.

Get current epoch or Unix timestamp in Go

We can get the current epoch or timestamp using Go time() package. It returns the current epoch in the number of seconds.

import "time"
time.Now().Unix()


Output
1585990763

Convert epoch or Unix timestamp to date in Go

We can convert the epoch or timestamp to readable date format using time() package. The function formats and return epoch or timestamp to human readable date and time.

timestamp := 1585990763
myDate := time.Unix(timestamp, 0)
fmt.Println(myDate)


Output
2020-04-04 02:35:46 +0000 UTC

Convert date to epoch or unix timestamp in Go

We can convert human readable date to timestamp using time() package. The function convert English textual datetime into a Unix timestamp.

package main
import (
"time"
"fmt"
"os"
)
func main() {
thetime, e := time.Parse(time.RFC3339, "2020-04-04T22:08:41+00:00")
if e != nil {
panic("Can't parse time format")
}
epoch := thetime.Unix()
fmt.Fprintf(os.Stdout, "Epoch: %d\n", epoch)
}


Output
Epoch: 1586038121


More about date time in Go