Epoch in Go

Go: Epoch

What is Epoch?

In computing, an epoch is a reference point used to measure time. In Unix and many other operating systems, the epoch is defined as the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC. This value is often referred to as the Unix timestamp.

In Go, we can work with epochs using the time package, which provides functionality for working with dates and times. The time package includes the time.Unix() function, which allows you to convert a Unix timestamp (i.e. the number of seconds since the epoch) into a time.Time value.

How to convert a Unix timestamp into a time.Time value in Go

Here's an example of how to convert a Unix timestamp into a time.Time value:

    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        unixTime := int64(1615594458) // Unix timestamp for March 13, 2021, 11:47:38 UTC
        timeObj := time.Unix(unixTime, 0)
        fmt.Println(timeObj) // Output: 2021-03-13 11:47:38 +0000 UTC
    }

The time.Unix() function takes two arguments: the first argument is the Unix timestamp (as an int64 value), and the second argument is the number of nanoseconds past the Unix timestamp (optional, defaults to 0). The function returns a time.Time value representing the corresponding date and time.

How to convert time.Time value into a Unix timestamp value in Go

You can also convert a time.Time value into a Unix timestamp using the Time.Unix() method:

    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        timeObj := time.Date(2021, 3, 13, 11, 47, 38, 0, time.UTC)
        unixTime := timeObj.Unix()
        fmt.Println(unixTime) // Output: 1615594458
    }

In this example, the time.Date() function is used to create a time.Time value representing March 13, 2021, 11:47:38 UTC.

The Time.Unix() method is then used to convert this value into a Unix timestamp (i.e. the number of seconds since the epoch).