如何在 Go 中获取一天中的秒数 (1 - 86400)?
就像http://joda-time.sourceforge.net/apidocs/org/joda/time/base/AbstractDateTime.html#getSecondOfDay()
更新/澄清
- 想要相当于 golang 中的 joda/SecondOfDay
- 预计在当天结束时从 0 点开始到 86400 点
- 在 golang 中重写 java 开源函数时需要,而该函数又使用 joda/secondOfDay
- 用 Google 搜索“24 小时到秒”得到 86400
- 在提问时我只能想到 now.Unix()-yesterdayMidnight.Unix() 而我并没有想到简单的可接受的答案
- 显然没有考虑夏令时
- 想看看是否有一些内置函数或流行/标准库
如果我们将“一天中的秒数”定义为“自午夜以来经过的秒数”,那么即使在 daylight saving time 的日子里也能得到正确的结果碰巧我们应该从给定时间中减去代表午夜的时间。为此,我们可以使用 Time.Sub()
.
func daySeconds(t time.Time) int {
year, month, day := t.Date()
t2 := time.Date(year, month, day, 0, 0, 0, 0, t.Location())
return int(t.Sub(t2).Seconds())
}
测试它:
for _, t := range []time.Time{
time.Date(2019, 1, 1, 0, 0, 30, 0, time.UTC),
time.Date(2019, 1, 1, 0, 1, 30, 0, time.UTC),
time.Date(2019, 1, 1, 0, 12, 30, 0, time.UTC),
time.Date(2019, 1, 1, 12, 12, 30, 0, time.UTC),
} {
fmt.Println(daySeconds(t))
}
输出(在 Go Playground 上尝试):
30
90
750
43950
让我们看看这个函数如何在夏令时时给出正确的结果。在匈牙利,2018 年 3 月 25 日是时钟在 02:00:00
拨快 1 小时的一天,从 2 am
到 3 am
.
loc, err := time.LoadLocation("CET")
if err != nil {
fmt.Println(err)
return
}
t := time.Date(2018, 3, 25, 0, 0, 30, 0, loc)
fmt.Println(t)
fmt.Println(daySeconds(t))
t = t.Add(2 * time.Hour)
fmt.Println(t)
fmt.Println(daySeconds(t))
此输出(在 Go Playground 上尝试):
2018-03-25 00:00:30 +0100 CET
30
2018-03-25 03:00:30 +0200 CEST
7230
我们打印午夜后 30 秒的 daySeconds
,当然是 30
。然后我们将时间加上 2 小时(2 小时 = 2*3600 秒 = 7200),这个新时间的 daySeconds
将正确地为 7200 + 30 = 7230
,即使时间改变了 3 小时。