date - Go 中的最大 time.Time 是多少?

标签 date time go

我正在寻找有关 Max time.Time 的文档。

其他语言使其显式化,例如在 C# 中:http://msdn.microsoft.com/en-us/library/system.datetime.maxvalue(v=vs.110).aspx

public static readonly DateTime MaxValue

The value of this constant is equivalent to 23:59:59.9999999, December 31, 9999, exactly one 100-nanosecond tick before 00:00:00, January 1, 10000.

Go 中的最大 time.Time 是多少?它是否记录在某处?

最佳答案

time.Time在 go 中存储为 int64 加上 32 位纳秒值,但如果您使用@JimB 的答案,您将在 sec 上触发整数溢出。组件和比较,如 time.Before()将不起作用。

这是因为 time.Unix(sec, nsec)将 62135596800 秒的偏移量添加到 sec表示第 1 年(Go 中的零时间)和 1970 年(Unix 中的零时间)之间的秒数。

@twotwotwo 的 Playground 示例在 http://play.golang.org/p/i6S_T4-X3v 中清楚地说明了这一点但这是一个精简版。

// 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))

因此虽然有点麻烦,但您可以使用 time.Unix(1<<63-62135596801, 999999999)如果你想要最大 time.Time这对于比较很有用,例如在某个时间范围内找到最小值。

关于date - Go 中的最大 time.Time 是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25065055/

相关文章:

MySQL 日期精度

java - 查找并返回第二天日期字符串的最佳方法?

go - 如何使用 golang 中的 api 编辑 GCP 云存储中的现有数据

go - 范围的奇怪行为

debugging - Windows 10上的Delve for Go中的代码显示问题

javascript - sethours 更新时间部分,但不更新日期时间字段中的日期部分

java 。无法使用 DateFormat 解析日期

java - 将秒转换为人类可读格式 MM :SS Java

java - 识别正在播放的音频文件的运行时间

c++ - 如何将 EPOCH 时间转换为时间格式 (hh :mm)