2 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個(gè)贊
為避免 DST(夏令時(shí))和其他錯(cuò)誤,在持續(xù)時(shí)間內(nèi)使用 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貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
peterSO 的回答是正確的。我用上面的代碼解決了這個(gè)問題:
endDate := time.Date(now.Year(), now.Month(), now.Day(), 23, 45, 0, now.Nanosecond(), now.Location())
如果有人遇到這樣的問題,他們可以選擇其中一個(gè)。
- 2 回答
- 0 關(guān)注
- 183 瀏覽
添加回答
舉報(bào)