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.
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).
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go