What is the maximum time.Time in Go?

time.Time in go is stored as an int64 plus a 32-bit nanosecond value, but if you use @JimB's answer you will trigger an integer overflow on the sec component and comparisons like time.Before() will not work.

This is because time.Unix(sec, nsec) adds an offset of 62135596800 seconds to sec that represents the number of seconds between the year 1 (zero time in Go) and 1970 (zero time in Unix).

@twotwotwo's playground example makes this clear in http://play.golang.org/p/i6S_T4-X3v but here is a distilled version.

// number of seconds between Year 1 and 1970 (62135596800 seconds)
unixToInternal := int64((1969*365 + 1969/4 - 1969/100 + 1969/400) * 24 * 60 * 60)

// max1 gets time.Time struct: {-9223371974719179009 999999999}
max1 := time.Unix(1<<63-1, 999999999)
// max2 gets time.Time struct: {9223372036854775807 999999999}
max2 := time.Unix(1<<63-1-unixToInternal, 999999999)

// t0 is definitely before the year 292277026596
t0 := time.Date(2015, 9, 16, 19, 17, 23, 0, time.UTC)

// t0 < max1 doesn't work: prints false
fmt.Println(t0.Before(max1))
// max1 < t0 doesn't work: prints true
fmt.Println(t0.After(max1))
fmt.Println(max1.Before(t0))

// t0 < max2 works: prints true
fmt.Println(t0.Before(max2))
// max2 < t0 works: prints false
fmt.Println(t0.After(max2))
fmt.Println(max2.Before(t0))

So while it is a bit of a pain you can use time.Unix(1<<63-62135596801, 999999999) if you want a max time.Time that is useful for comparisons like finding the minimum value in a range of times.


Time in go is stored as an int64 plus a 32bit Nanosec value (currently a uintptr for technical reasons), so there's no real worry about running out.

t := time.Unix(1<<63-1, 0)
fmt.Println(t.UTC())

prints 219250468-12-04 15:30:07 +0000 UTC

If for some reason you want a useful max time (see @cce's answer for details), you can use:

maxTime := time.Unix(1<<63-62135596801, 999999999)

Tags:

Time

Date

Go