Epoch in Go
Golang Concepts
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.
time.Time
value in Go
How to convert a Unix timestamp into a 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.
time.Time
value into a Unix timestamp value in Go
How to convert 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).