How to get the epoch timestamp in Go lang?

Posted on

In 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)
}

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

2 comments

    1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *