Ulug'bek
Ulug'bek

Reputation: 2832

Go: error getting difference between two time

I have one headache with time. I have above code:

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

At my comp now and endDate have different time zone:

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

That's why get wrong duration. How can I set same time zone to both of them ? And a problem again, pay attantion when ticker tik first and second duration has differens 5 hour. Why those problems have occured. What am I doing wrong? Do you have any idea ? Made me happe any hint from you ?

Upvotes: 2

Views: 122

Answers (2)

Ulug'bek
Ulug'bek

Reputation: 2832

peterSO's answer is right. And I solved the problem with above code:

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

If somebody come accross with a problem like that they can choose ine of them.

Upvotes: 1

peterSO
peterSO

Reputation: 166935

To avoid DST (Daylight Savings Time) and other errors use UTC for the duration. For example,

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

Output:

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

Upvotes: 3

Related Questions