The Unix epoch is a specific point in time, represented as the number of seconds that have elapsed since 00:00:00 UTC on January 1, 1970. In Go, the time
package provides a Time
type that can be used to represent times as the number of nanoseconds elapsed since the Unix epoch.
Here’s an example that demonstrates how to use the time
package to get the current time as a Unix timestamp, and how to convert a Unix timestamp back into a Time
value:
package main
import (
"fmt"
"time"
)
func main() {
// Get the current time as a Unix timestamp
timestamp := time.Now().Unix()
fmt.Println("Current Unix timestamp:", timestamp)
// Convert a Unix timestamp into a Time value
t := time.Unix(timestamp, 0)
fmt.Println("Time from Unix timestamp:", t)
}
In this example, the time.Now
function is used to get the current time, and the Unix
method is used to get the current time as a Unix timestamp. The time.Unix
function is then used to convert the Unix timestamp back into a Time
value, which is stored in the t
variable.
The output of this program will be something like:
Current Unix timestamp: 1649402274
Time from Unix timestamp: 2022-11-22 10:13:14 +0100 CET
Leave a Reply