How do you convert a very large (>max(int64)) nanosecond unix timestamp to time.Time

Viewed 645

I have a uint64 nanosecond unix timestamp which is larger than than the max value a int64 can hold. Since I can no longer use the time.Unix() function which takes int64, how can I convert this timestamp to a Time without losing data?

1 Answers

The time.Unix() function takes 2 arguments:

func Unix(sec int64, nsec int64) Time

If you have the int64 nanoseconds, you may pass 0 for sec, and the nanoseconds value for nsec. For example:

nsec := int64(1623840300988135567)
t := time.Unix(0, nsec)
fmt.Println(t) // 2021-06-16 10:45:00.988135567 +0000 UTC

It is valid to pass nanoseconds value outside the range [0, 999999999].

If you have a nanoseconds value not fitting into int64, then simply break it into 2 parts: seconds and remaining nanoseconds. Breaking it is simply dividing by and getting the remainder of dividing by 1e9 (which is the number of nanoseconds in a sec).

For example:

x := uint64(math.MaxInt64)
t = time.Unix(0, int64(x))
fmt.Println(t)

x += uint64(time.Hour)
t = time.Unix(int64(x/1e9), int64(x%1e9))
fmt.Println(t)

Adding time.Hour to math.MaxInt64 clearly doesn't fit into int64. Yet the above code runs fine and outputs:

2262-04-11 23:47:16.854775807 +0000 UTC
2262-04-12 00:47:16.854775807 +0000 UTC

Try it on the Go Playground.

Related