go - 如何获得一天中的秒数

标签 go time

<分区>

如何在 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 am3 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 小时。

关于go - 如何获得一天中的秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55023060/

相关文章:

go - 如何从 Golang 的子目录中正确导入包?

android - Android 上运行的 Go 程序如何访问互联网?

postgresql - 使用 gorm 检索没有模型的记录

SQLite 查询日期等于今天

ios - 如何将我的 UILabel 与系统时间同步?

Go 中的 Rest API——使用 net/http 与像 Gorilla 这样的库

php - 将 cookie curl 到 Golang HTTP 请求

r - 将数字转换为 HH :MM:SS

powershell - 将时间和日期戳添加到导出的文件

php - 如何用土耳其语显示 PHP 日期?