我正在寻找有关Max time.Time的文档.
其他语言使其明确,例如在C#中:http://msdn.microsoft.com/en-us/library/system.datetime.maxvalue(v = vs.110).aspx
public static readonly DateTime MaxValue
Run Code Online (Sandbox Code Playgroud)
该常数的值相当于23:59:59.9999999,12999年12月31日,恰好在10000点之前的00:00:00之前的一个100纳秒刻度.
Go的最长时间是多长时间?它在某处记录了吗?
cce*_*cce 16
time.Time在go中存储为int64加上32位纳秒值,但如果使用@ JimB的答案,则会触发sec组件上的整数溢出,并且比较time.Before()不起作用.
这是因为它time.Unix(sec, nsec)增加了62135596800秒的偏移量sec,表示第1年(Go中的零时间)和1970(Unix中的零时间)之间的秒数.
@ twotwotwo的游乐场示例在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))
Run Code Online (Sandbox Code Playgroud)
因此,time.Unix(1<<63-62135596801, 999999999)如果您想要一个time.Time对比较有用的最大值,例如在一定范围内找到最小值,那么您可以使用它.
Jim*_*imB 15
go的时间存储为int64加上32bit Nanosec值(由于技术原因目前是uintptr),因此没有真正担心耗尽.
t := time.Unix(1<<63-1, 0)
fmt.Println(t.UTC())
Run Code Online (Sandbox Code Playgroud)
版画 219250468-12-04 15:30:07 +0000 UTC
如果由于某种原因你想要一个有用的最长时间(详见@ cce的答案),你可以使用:
maxTime := time.Unix(1<<63-62135596801, 999999999)
Run Code Online (Sandbox Code Playgroud)
请注意,尽管 @cce 的答案可以确保After并且Before将会起作用,但其他 API 则不会。UnixNano仅在 1970 年左右(1678 年至 2262 年之间)的 \xc2\xb1292 年内有效。此外,由于最长持续时间约为 292 年,因此即使这两者也会在 上给出固定结果Sub。
因此,另一种方法是选择一个最小值[1]值并执行以下操作:
\nvar MinTime = time.Unix(-2208988800, 0) // Jan 1, 1900\nvar MaxTime = MinTime.Add(1<<63 - 1)\nRun Code Online (Sandbox Code Playgroud)\n在这些范围内,一切都应该有效。
\n[1]:另一个明显的选择是time.Unix(0, 0)如果您不关心 1970 年之前的日期。