Shibasis Patel
Shibasis Patel

Reputation: 315

Why does the time conversion depend on the date?

I am storing the time as "02:00:00" in my DB. But I want to show this time as my local timezone.

I tried to do this to convert the time from UTC to Asia/Jakarta time:

package main
import (
    "fmt"
    "time"
)
func main() {
    layout := "15:04:05"
    inTimeStr := "02:00:00"
    loc, _ := time.LoadLocation("Asia/Jakarta")
    inTime, _ := time.Parse(layout, inTimeStr)
    fmt.Println(inTime)
    fmt.Println(inTime.In(loc).Format(layout))
}

I expected this to be 09:00:00 but surprisingly it was 09:07:12.

I tried to change the year of the time to different values and I got different result. For me, it gave correct result if I set the year to 1970 or more.

Playground link: https://play.golang.org/p/o0nj15CRHud

Upvotes: 2

Views: 144

Answers (2)

Lars Christian Jensen
Lars Christian Jensen

Reputation: 1642

time.Parse returns Time (https://golang.org/pkg/time/#Time) which represents an instant in time (including the date). Elements omitted from the value are assumed to be zero, so the time you get when parsing 02:00:00 is 0000-01-01 02:00:00 +0000 UTC.

You get the expected result when setting the year to 1970 or more because the time zones have changed historically (see comment from Nate Eldredge).

Upvotes: 4

Burak Serdar
Burak Serdar

Reputation: 51632

When you use inTime.In, it converts the time (which is in UTC) into that timezone. You should use ParseInLocation instead of Parse to interpret the parsed time in the given location.

Upvotes: 2

Related Questions