Go Unix Timestamp Guide
A comprehensive guide to working with Unix timestamps in Go. Learn how to get the current timestamp, convert between timestamps and time.Time objects, format dates, and handle timezones.
Quick Reference
Get Current Timestamp
time.Now().Unix()Timestamp to Time
time.Unix(timestamp, 0)Time to Timestamp
t.Unix()Current UTC Time
time.Now().UTC()Getting the Current Unix Timestamp
The time package provides methods to get the current Unix timestamp:
package main
import (
"fmt"
"time"
)
func main() {
// Get current timestamp (seconds since Jan 1, 1970)
timestamp := time.Now().Unix()
fmt.Println(timestamp) // Output: 1733616000
// Get timestamp in milliseconds
timestampMs := time.Now().UnixMilli()
fmt.Println(timestampMs) // Output: 1733616000123
// Get timestamp in microseconds
timestampUs := time.Now().UnixMicro()
fmt.Println(timestampUs) // Output: 1733616000123456
// Get timestamp in nanoseconds
timestampNs := time.Now().UnixNano()
fmt.Println(timestampNs) // Output: 1733616000123456789
}Note: Go's time package provides nanosecond precision. Use the appropriate method based on your needs.
Converting Timestamp to Time
Convert a Unix timestamp to a time.Time object:
package main
import (
"fmt"
"time"
)
func main() {
// Convert timestamp (seconds) to time.Time
timestamp := int64(1733616000)
t := time.Unix(timestamp, 0)
fmt.Println(t) // Output: 2024-12-07 18:00:00 +0000 UTC
// Convert millisecond timestamp
timestampMs := int64(1733616000123)
tMs := time.UnixMilli(timestampMs)
fmt.Println(tMs) // Output: 2024-12-07 18:00:00.123 +0000 UTC
// Convert microsecond timestamp
timestampUs := int64(1733616000123456)
tUs := time.UnixMicro(timestampUs)
fmt.Println(tUs) // Output: 2024-12-07 18:00:00.123456 +0000 UTC
// Convert with nanoseconds
t2 := time.Unix(1733616000, 123456789)
fmt.Println(t2) // Output: 2024-12-07 18:00:00.123456789 +0000 UTC
// Format the time
formatted := t.Format("2006-01-02 15:04:05")
fmt.Println(formatted) // Output: 2024-12-07 18:00:00
// Format using predefined layouts
fmt.Println(t.Format(time.RFC3339))
// Output: 2024-12-07T18:00:00Z
}Converting Time to Timestamp
Convert a time.Time object to a Unix timestamp:
package main
import (
"fmt"
"time"
)
func main() {
// Current time to timestamp
now := time.Now()
timestamp := now.Unix()
fmt.Println(timestamp) // Output: 1733616000
// Specific date to timestamp
t := time.Date(2024, time.December, 7, 18, 0, 0, 0, time.UTC)
timestamp2 := t.Unix()
fmt.Println(timestamp2) // Output: 1733616000
// Parse string date to timestamp
layout := "2006-01-02 15:04:05"
dateString := "2024-12-07 18:00:00"
t2, err := time.Parse(layout, dateString)
if err != nil {
panic(err)
}
timestamp3 := t2.Unix()
fmt.Println(timestamp3) // Output: 1733616000
// Get millisecond timestamp
timestampMs := now.UnixMilli()
fmt.Println(timestampMs) // Output: 1733616000123
// Get microsecond timestamp
timestampUs := now.UnixMicro()
fmt.Println(timestampUs) // Output: 1733616000123456
// Get nanosecond timestamp
timestampNs := now.UnixNano()
fmt.Println(timestampNs) // Output: 1733616000123456789
}Working with Timezones
Handle timezone-aware timestamps using the time package:
package main
import (
"fmt"
"time"
)
func main() {
// Load timezone locations
utc, _ := time.LoadLocation("UTC")
ny, _ := time.LoadLocation("America/New_York")
tokyo, _ := time.LoadLocation("Asia/Tokyo")
// Create time in specific timezone
timestamp := int64(1733616000)
tUTC := time.Unix(timestamp, 0).In(utc)
tNY := time.Unix(timestamp, 0).In(ny)
tTokyo := time.Unix(timestamp, 0).In(tokyo)
fmt.Println("UTC: ", tUTC)
// Output: 2024-12-07 18:00:00 +0000 UTC
fmt.Println("NY: ", tNY)
// Output: 2024-12-07 13:00:00 -0500 EST
fmt.Println("Tokyo: ", tTokyo)
// Output: 2024-12-08 03:00:00 +0900 JST
// Get current time in specific timezone
nowNY := time.Now().In(ny)
fmt.Println(nowNY)
// Convert between timezones
converted := tUTC.In(tokyo)
fmt.Println("Converted:", converted)
// Use local timezone
local := time.Now().Local()
fmt.Println("Local:", local)
}Formatting and Parsing Times
Format and parse time strings in Go:
package main
import (
"fmt"
"time"
)
func main() {
timestamp := int64(1733616000)
t := time.Unix(timestamp, 0)
// Custom format (use reference time: Mon Jan 2 15:04:05 MST 2006)
fmt.Println(t.Format("2006-01-02 15:04:05"))
// Output: 2024-12-07 18:00:00
fmt.Println(t.Format("Jan 02, 2006 at 3:04 PM"))
// Output: Dec 07, 2024 at 6:00 PM
// Predefined layouts
fmt.Println(t.Format(time.RFC3339))
// Output: 2024-12-07T18:00:00Z
fmt.Println(t.Format(time.RFC822))
// Output: 07 Dec 24 18:00 UTC
fmt.Println(t.Format(time.UnixDate))
// Output: Sat Dec 7 18:00:00 UTC 2024
// Parse string to time
layout := "2006-01-02 15:04:05"
str := "2024-12-07 18:00:00"
parsed, err := time.Parse(layout, str)
if err != nil {
panic(err)
}
fmt.Println(parsed.Unix()) // Output: 1733616000
// Parse with timezone
parsedTZ, _ := time.Parse(time.RFC3339, "2024-12-07T18:00:00Z")
fmt.Println(parsedTZ.Unix())
}Important: Go uses a reference time Mon Jan 2 15:04:05 MST 2006 for formatting. Use this exact date/time to create your custom layouts.
Common Use Cases
Calculate Time Difference
package main
import (
"fmt"
"time"
)
func main() {
// Calculate difference between two timestamps
timestamp1 := int64(1733616000)
timestamp2 := int64(1733619600)
t1 := time.Unix(timestamp1, 0)
t2 := time.Unix(timestamp2, 0)
// Get duration
diff := t2.Sub(t1)
fmt.Printf("Difference: %v\n", diff)
// Output: Difference: 1h0m0s
fmt.Printf("Hours: %.2f\n", diff.Hours())
// Output: Hours: 1.00
fmt.Printf("Minutes: %.0f\n", diff.Minutes())
// Output: Minutes: 60
fmt.Printf("Seconds: %.0f\n", diff.Seconds())
// Output: Seconds: 3600
// Check if time is before/after
if t1.Before(t2) {
fmt.Println("t1 is before t2")
}
}Add/Subtract Time
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
// Add time
future := now.Add(24 * time.Hour)
fmt.Println("Tomorrow:", future)
// Add multiple units
future2 := now.Add(2*time.Hour + 30*time.Minute)
fmt.Println("+2.5 hours:", future2)
// Subtract time
past := now.Add(-7 * 24 * time.Hour)
fmt.Println("Week ago:", past)
// Add days/months/years
nextMonth := now.AddDate(0, 1, 0)
fmt.Println("Next month:", nextMonth)
nextYear := now.AddDate(1, 0, 0)
fmt.Println("Next year:", nextYear)
// Specific date operations
yesterday := now.AddDate(0, 0, -1)
fmt.Println("Yesterday:", yesterday)
}Get Start of Day
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
// Start of day (00:00:00)
startOfDay := time.Date(
now.Year(),
now.Month(),
now.Day(),
0, 0, 0, 0,
now.Location(),
)
fmt.Println("Start of day:", startOfDay)
fmt.Println("Timestamp:", startOfDay.Unix())
// End of day (23:59:59)
endOfDay := time.Date(
now.Year(),
now.Month(),
now.Day(),
23, 59, 59, 0,
now.Location(),
)
fmt.Println("End of day:", endOfDay)
fmt.Println("Timestamp:", endOfDay.Unix())
}Best Practices
Always use time.Time for comparisons
Don't compare timestamps directly; convert to time.Time first.
Store timestamps in UTC
Use UTC for storage and convert to local time only for display.
Use the reference time for formatting
Remember: Mon Jan 2 15:04:05 MST 2006 is the reference time.
Handle timezone loading errors
Always check errors when using time.LoadLocation().
Use int64 for timestamps
Unix() returns int64 to avoid Year 2038 problem.
Be aware of monotonic clocks
time.Now() includes a monotonic clock reading for accurate duration measurements.