英文:
Is it safe to use time.Now().Unix(), UnixNano(), UnixMilli() etc? What about integer overflow?
问题
我在这里阅读到https://pkg.go.dev/time#Unix,Unix()函数返回的是“给定的Unix时间戳,从1970年1月1日UTC开始计算的秒数和纳秒数所对应的本地时间”。
而你也可以使用UnixNano()和UnixMilli()分别获取自1970年以来的毫秒数和纳秒数。
我猜我对这个是如何安全的感到困惑。难道不会有一个日期/时间截止点,超过int64的容量,导致纳秒、毫秒或常规秒数的数量超过范围吗?
此外,我在go playground上进行实验,通过打印出"time.Now.Unix()",即使我在代码运行时相隔一分钟,我总是得到1257894000秒。
然而,如果我这样做:
time.Now.Unix()
time.Sleep(time.Duration(1) * time.Second)
time.Now.Unix()
这将给我1257894000和1257894001。
我对Unix时间的工作原理感到困惑。
英文:
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.
答案1
得分: 4
Time.Unix()
、Time.UnixMicro()
、Time.UnixMilli()
、Time.UnixNano()
都返回有符号的int64类型。
有符号的int64的最大值是9,223,372,036,854,775,807。
这意味着Time.Unix()
在未来的2920亿年内不会用完整数。它无疑会比人类存在更久。
最糟糕的情况是Time.UnixNano()
,它将在2262年4月11日星期五晚上11:47:16.854 GMT
用完整数。我不知道你怎么看,但我会已经去世了,希望没有人会使用我的代码。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论