Golang Timestamp Conversions

Golang provides a number of built-in functions for converting timestamps to different formats. In this article, we will discuss various types of timestamp conversions in Golang.

Converting Timestamp to Time

To convert a Unix timestamp to a time.Time object, we can use the Unix() function of the time package.

Example:
1 2 3 4 5 6 7 8 9 10 11 12package main import ( "fmt" "time" ) func main() { unixTimestamp := int64(1615460256) // timestamp in seconds timeObj := time.Unix(unixTimestamp, 0) fmt.Println(timeObj) // 2021-03-11 12:17:36 +0000 UTC }

Converting Time to Timestamp

To convert a time.Time object to a Unix timestamp, we can use the Unix() function of the time package.

Example:
1 2 3 4 5 6 7 8 9 10 11 12package main import ( "fmt" "time" ) func main() { t := time.Now() unixTimestamp := t.Unix() fmt.Println(unixTimestamp) // 1615501798 }

Converting Timestamp to RFC3339 Format

RFC3339 is a standard format for representing dates and times in textual form. To convert a Unix timestamp to the RFC3339 format, we can use the Format() function of the time package.

Example:
1 2 3 4 5 6 7 8 9 10 11 12 13package main import ( "fmt" "time" ) func main() { unixTimestamp := int64(1615460256) // timestamp in seconds timeObj := time.Unix(unixTimestamp, 0) rfc3339Time := timeObj.Format(time.RFC3339) fmt.Println(rfc3339Time) // 2021-03-11T12:17:36Z }

Converting RFC3339 Time to Timestamp

To convert a time in the RFC3339 format to a Unix timestamp, we can use the Parse() function of the time package.
1 2 3 4 5 6 7 8 9 10 11 12 13package main import ( "fmt" "time" ) func main() { rfc3339Time := "2021-03-11T12:17:36Z" timeObj, _ := time.Parse(time.RFC3339, rfc3339Time) unixTimestamp := timeObj.Unix() fmt.Println(unixTimestamp) // 1615460256 }

Converting Timestamp to Custom Format

To convert a Unix timestamp to a custom format, we can use the Format() function of the time package and provide a format string.

Example:
1 2 3 4 5 6 7 8 9 10 11 12 13package main import ( "fmt" "time" ) func main() { unixTimestamp := int64(1615460256) // timestamp in seconds timeObj := time.Unix(unixTimestamp, 0) customTime := timeObj.Format("02 Jan 2006 15:04:05 MST") fmt.Println(customTime) // 11 Mar 2021 12:17:36 UTC }

Converting Custom Time to Timestamp

To convert a time in a custom format to a Unix timestamp, we can use the Parse() function of the time package and provide a format string.

1 2 3 4 5 6 7 8 9 10 11 12 13package main import ( "fmt" "time" ) func main() { customTime := "11 Mar 2021 12:17:36 UTC" timeObj, _ := time.Parse("02 Jan 2006 15:04:05 MST", customTime) unixTimestamp := timeObj.Unix() fmt.Println(unixTimestamp) // 1615460256 }
© 2024 made by www.epochconverter.io