Go:获取两次时间差时出错

Go: error getting difference between two time

我有一个 headache 有时间。我有上面的代码:

// ticker := time.NewTicker(time.Minute * 1)
    ticker := time.NewTicker(time.Second * 1)
    defer ticker.Stop()

    // new version
    for t := range ticker.C {

        // get duration

        go func() {
            now := time.Now()
            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)

            drHours := (duration.Minutes() - math.Mod(duration.Minutes(), 60)) / 60
            drMinutes := math.Mod(duration.Minutes(), 60)
            //fmt.Println(duration.Hours())

            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)
    }

在我的 nowendDate 有不同的时区:

2015-11-12 10:33:53.9298552 +0500 UZT  // now
2015-11-12 23:45:00 +0000 UTC          // endDate

这就是持续时间错误的原因。如何为它们设置相同的时区? 还有一个问题,当 ticker tik 第一次和第二次持续时间相差 5 小时时要注意。为什么会出现这些问题。我究竟做错了什么?你有什么主意吗 ?你给我的任何提示让我很开心?

为避免 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

是对的。我用上面的代码解决了这个问题:

endDate := time.Date(now.Year(), now.Month(), now.Day(), 23, 45, 0, now.Nanosecond(), now.Location())

如果有人遇到这样的问题,他们可以选择其中之一。