2 回答
TA贡献1829条经验 获得超9个赞
为避免 DST(夏令时)和其他错误,在持续时间内使用 UTC。例如,
package main
import (
"fmt"
"math"
"time"
)
func main() {
ticker := time.NewTicker(time.Second * 1)
defer ticker.Stop()
for t := range ticker.C {
go func() {
now := time.Now().UTC()
const layout = "2006-01-02 15:04:05"
endDateStr := fmt.Sprintf("%04d-%02d-%02d 23:45:00", now.Year(), now.Month(), now.Day())
endDate, _ := time.Parse(layout, endDateStr)
duration := endDate.Sub(now)
drMinutes := math.Mod(duration.Minutes(), 60)
drHours := (duration.Minutes() - drMinutes) / 60
fmt.Println(now)
fmt.Println(endDate)
durStr := fmt.Sprintf("%d:%d:00", uint64(drHours), uint64(drMinutes))
fmt.Printf("duration: %s\n", durStr)
}()
fmt.Println(t.UTC())
}
}
输出:
2015-11-12 06:41:40.123232567 +0000 UTC
2015-11-12 06:41:40.123409615 +0000 UTC
2015-11-12 23:45:00 +0000 UTC
duration: 17:3:00
TA贡献2011条经验 获得超2个赞
peterSO 的回答是正确的。我用上面的代码解决了这个问题:
endDate := time.Date(now.Year(), now.Month(), now.Day(), 23, 45, 0, now.Nanosecond(), now.Location())
如果有人遇到这样的问题,他们可以选择其中一个。
- 2 回答
- 0 关注
- 148 浏览
添加回答
举报