Convert Unix timestamp to time in Go and vice versa

0
1227
Convert Unix timestamp to time in Go and vice versa
Convert Unix timestamp to time in Go and vice versa

Today, I will you a useful tip to convert Unix timestamp to time in Go and vice versa.

Unix timestamp to time

To convert Unix timestamp to time.Time in Go, we will use time.Unix(sec int64, nsec int64) function for the job.

var ts int64 = 1655246547

toTime := time.Unix(ts, 0)

fmt.Printf("time.Time: %s\n", toTime)

Once compiling and run, it should output result like this:

time.Time: 2022-06-14 22:42:27 +0000 UTC

time to Unix timestamp

To get Unix timestamp from the time.Time object, we will use time.Unix() function, it will return value as int64.

fromTime := time.Now()

ts := fromTime.Unix()

fmt.Printf("Unix timestamp: %d\n", ts)

Your output should be something similar to this: (since time.Now() is used to generate time object, the output will vary based on the time when you execute the program)

Unix timestamp: 1655269626

Conclusion

That’s how you convert Unix timestamp to time in Go and vice versa.

Have fun!