0

I read here https://pkg.go.dev/time#Unix that Unix() returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC

And you can also get the milliseconds since, or nanoseconds since 1970 using UnixNano() and UnixMilli() respectively.

I guess I'm confused as to how this is safe. Won't there be a date/time cut off where the number of nano, milli or regular seconds exceeds int64's capacity?

Also, I was experimenting on go playground https://go.dev/play/ by printing out time.Now.Unix(), I would always get 1257894000 seconds, even if I ran my code like a minute apart.

However I did see a difference if I did

time.Now.Unix()
time.Sleep(time.Duration(1) * time.Second)
time.Now.Unix()

Which gave me 1257894000 and 1257894001.

I'm confused how Unix time works basically.

Shisui
  • 1,051
  • 1
  • 8
  • 23
  • (((9223372036854775807/(10^9))/60)/24)/365 = 17548.27 years. We will not survive long enough to see it. – nilsocket Mar 21 '22 at 00:31
  • 1
    Of course there's a cutoff. Unless you have infinite capacity, there's always a cutoff. the question is whether it's a relevant cutoff. – Jonathan Hall Mar 21 '22 at 00:36
  • The playground page where you ran the program explains why you see the same time over server runs of the program: *In the playground the time begins at 2009-11-10 23:00:00 UTC (determining the significance of this date is an exercise for the reader). This makes it easier to cache programs by giving them deterministic output.* –  Mar 21 '22 at 00:52

1 Answers1

4

Time.Unix(), Time.UnixMicro(), Time.UnixMilli(), Time.UnixNano() all return signed int64s.

The max signed int64 is 9,223,372,036,854,775,807

This means Time.Unix() won't run out of integers for 292 billion years. It will undoubtedly outlive humanity.

The worst case scenario is Time.UnixNano() which will run out of integers on Friday, April 11, 2262 11:47:16.854 PM GMT. I don't know about you, but I'll be dead and hopefully no one will be using my code.

donatJ
  • 3,105
  • 3
  • 32
  • 51