如何将一个非常大的(大于max(int64))纳秒级Unix时间戳转换为time.Time类型?

huangapple go评论76阅读模式
英文:

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

问题

我有一个大于int64可以容纳的最大值的uint64纳秒级Unix时间戳。由于我不能再使用接受int64参数的time.Unix()函数,我该如何将这个时间戳转换为Time类型而不丢失数据呢?

英文:

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

得分: 6

time.Unix() 函数接受两个参数:

func Unix(sec int64, nsec int64) Time

如果你有 int64 类型的纳秒数,可以将 sec 参数设为 0,将纳秒数设为 nsec 参数。例如:

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

传递超出范围 [0, 999999999] 的纳秒数也是有效的。

如果你有一个无法适应 int64 类型的纳秒数,可以将其分为两部分:秒数和剩余的纳秒数。分割的方法是将其除以 1e9(即一秒钟的纳秒数)并取余数。

例如:

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)

time.Hour 加到 math.MaxInt64 上显然无法适应 int64 类型。然而,上述代码可以正常运行并输出:

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

Go Playground 上尝试一下吧。

英文:

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.

huangapple
  • 本文由 发表于 2021年6月16日 18:28:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/68000931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定