2

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Shibasis Patel
  • 315
  • 2
  • 14
  • 8
    It depends on the date because time zones changed historically. https://timezonedb.com/time-zones/Asia/Jakarta shows how civil time in this region has evolved. Prior to 1923 it was 7 hours 7.2 minutes off UTC, presumably because solar time was in use. – Nate Eldredge Apr 29 '21 at 20:06
  • 3
    Related: https://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result/6841479#6841479 – Nate Eldredge Apr 29 '21 at 20:08
  • See also [tz/asia, line 1333 ff.](https://github.com/eggert/tz/blob/a16541786b0d8c9746de8ed558c861550fdc3bc3/asia#L1333) – FObersteiner Apr 30 '21 at 09:18

2 Answers2

4

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

Lars Christian Jensen
  • 1,407
  • 1
  • 13
  • 14
2

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.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • [ParseInLocation](https://golang.org/pkg/time/#ParseInLocation) is a good hint, but for the OP's example, this still gives weird output due to the missing date (has to use LMT) - [playground ex](https://play.golang.org/p/Fnh76OCx9pK) – FObersteiner Apr 30 '21 at 09:13