Use time.Now().Unix() to get the current Unix timestamp in seconds, or time.Now().UnixNano() for nanoseconds. Both methods return an int64 representing the number of seconds or nanoseconds elapsed since January 1, 1970, UTC.
Here is the standard approach for getting the current timestamp:
package main
import (
"fmt"
"time"
)
func main() {
// Get current timestamp in seconds
seconds := time.Now().Unix()
fmt.Printf("Current timestamp (seconds): %d\n", seconds)
// Get current timestamp in nanoseconds
nanos := time.Now().UnixNano()
fmt.Printf("Current timestamp (nanoseconds): %d\n", nanos)
// Get timestamp for a specific time (e.g., New Year 2024)
specificTime := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
fmt.Printf("Specific timestamp: %d\n", specificTime.Unix())
}
If you need to convert a string or a specific date back into a Unix timestamp, parse the string first using time.Parse and then call .Unix() on the resulting time.Time object. Be careful with time zones; time.Now() returns the local time, but Unix() always calculates the offset from UTC, so the resulting integer is consistent regardless of your local timezone.
package main
import (
"fmt"
"time"
)
func main() {
// Parse a specific date string
t, err := time.Parse("2006-01-02 15:04:05", "2023-10-25 14:30:00")
if err != nil {
fmt.Println("Error parsing time:", err)
return
}
// Convert to Unix timestamp
ts := t.Unix()
fmt.Printf("Parsed timestamp: %d\n", ts)
// Convert timestamp back to time.Time
recoveredTime := time.Unix(ts, 0)
fmt.Printf("Recovered time: %s\n", recoveredTime.Format(time.RFC3339))
}
For high-precision requirements, prefer UnixNano() over Unix(), but be aware that UnixNano() returns a larger integer that can exceed 64-bit limits if you are dealing with dates far in the future or past (though this is rare in typical application logic). When storing timestamps in databases or APIs, seconds (Unix()) are the standard convention unless millisecond precision is explicitly required.