Confusing Time Issue

74 views
Skip to first unread message

jlfo...@berkeley.edu

unread,
Apr 21, 2023, 8:27:34 PM4/21/23
to golang-nuts
Consider the program below.

I want to compute the duration between a time that I put in the "old_time_str" variable and the current time. If I put the current time in a string, the program shows the correct duration. If I get the current time using time.Now() then the duration shown is 7 hours too long (I'm in PDST). I'd like both methods to return the correct duration. Let's presume that  both times are in the same time zone.

What am I doing wrong?

Cordially,
Jon Forrest

----------------------------
package main

import (
        "fmt"
        "time"
)

var old_time_str string = "Thu Apr 20 20:26:40 2023"
var new_time_str string = "Fri Apr 21 17:07:51 2023"
var time_format string = `Mon Jan 02 15:04:05 2006`

func main() {
        var new_time_1 time.Time
        var new_time_2 time.Time
        var old_time time.Time
        var diff time.Duration

        old_time, _ = time.Parse(time_format, old_time_str)
        new_time_1, _ = time.Parse(time_format, new_time_str)

        fmt.Printf("Old time is %s\n", old_time.Format(time_format))
        fmt.Printf("New time 1 is %s\n", new_time_1.Format(time_format))

        diff = new_time_1.Sub(old_time)
        fmt.Printf("diff 1: %s\n\n", diff.String())

        new_time_2 = time.Now()
        fmt.Printf("Old time is still %s\n", old_time.Format(time_format))
        fmt.Printf("New time 2 is %s\n", new_time_2.Format(time_format))

        diff = new_time_2.Sub(old_time)
        fmt.Printf("diff 2: %s\n", diff.String())
}

Ian Lance Taylor

unread,
Apr 21, 2023, 8:54:16 PM4/21/23
to jlfo...@berkeley.edu, golang-nuts
On Fri, Apr 21, 2023 at 5:27 PM jlfo...@berkeley.edu
<jlfo...@berkeley.edu> wrote:
>
> Consider the program below.
>
> I want to compute the duration between a time that I put in the "old_time_str" variable and the current time. If I put the current time in a string, the program shows the correct duration. If I get the current time using time.Now() then the duration shown is 7 hours too long (I'm in PDST). I'd like both methods to return the correct duration. Let's presume that both times are in the same time zone.
>
> What am I doing wrong?

It's timezones. Your time strings don't have any timezone
information, and the default differs for time.Parse and time.Now. You
will probably get the results you want if you change your calls to
time.Parse(t, s) to time.ParseInLocation(t, s, time.Local). See
https://pkg.go.dev/time#Parse.

Ian

jlfo...@berkeley.edu

unread,
Apr 21, 2023, 9:26:33 PM4/21/23
to golang-nuts
You're absolutely right, of course.

Jon

Reply all
Reply to author
Forward
0 new messages