How to get the epoch timestamp in Go lang?
Posted on In Programming, TutorialIn Go lang, how to get the epoch timestamp, the number of seconds passed since the epoch?
In Go, you can use the time.Now()
func to get current time and its Unix()
func to convert it into an epoch timestamp:
import("time")
func getEpochTime() int64 {
return time.Now().Unix()
}
If you would convert a time string to epoch timestamp, you can first parse the time string and then use the Unix()
function to convert it into an epoch timestamp as follows.
package main
import (
"time"
"fmt"
"os"
)
func main() {
thetime, e := time.Parse(time.RFC3339, "2012-11-01T22:08:41+00:00")
if e != nil {
panic("Can't parse time format")
}
epoch := thetime.Unix()
fmt.Fprintf(os.Stdout, "Epoch: %d\n", epoch)
}
But what if I need to convert a given date into epoch, instead of the current time?
You can use `Parse()` to parse a time string if you have the time string and call the `Unix()` function then. I added an example program to the post.