2

I am a golang developer and i am trying to convert a UTC time into local time but my code not working.Here is my code

utc := time.Now().UTC()
local := utc
location, err := time.LoadLocation("Asia/Delhi")
if err == nil {
   local = local.In(location)
}
log.Println("UTC", utc.Format("15:04"), local.Location(), local.Format("15:04"))
farsana p b
  • 165
  • 1
  • 12
  • Possible duplicate of [Convert UTC to "local" time - Go](https://stackoverflow.com/questions/25318154/convert-utc-to-local-time-go) – Mohsin Aljiwala Jul 11 '17 at 17:41
  • Replace `Asia/Delhi` with `Asia/Calcutta`. Refer [this](https://golang.org/src/time/zoneinfo_abbrs_windows.go) – Vallie Nov 28 '19 at 17:37

3 Answers3

4

You should rewrite your code to handle errors when they occur. The default execution path should be error free. So, after time.LoadLocation check if there is an error:

utc := time.Now().UTC()
local := utc
location, err := time.LoadLocation("Asia/Delhi")
if err != nil {
   // execution would stop, you could also print the error and continue with default values
   log.Fatal(err)
}
local = local.In(location)
log.Println("UTC", utc.Format("15:04"), local.Location(), local.Format("15:04"))

Now you'll get something like this error message:

cannot find Asia/Delhi in zip file /usr/local/go/lib/time/zoneinfo.zip
panic: time: missing Location in call to Time.In

You have to find a valid time zome for your location, as others said check Wikipedia for time zones

Kiril
  • 6,009
  • 13
  • 57
  • 77
3

You're getting an error on line 3, you just can't see it because it avoids the if block and so never updates the local variable on line 5.

The reason it fails is because 'Asia/Delhi' is not a valid olsen format.

Add an else block and print out the err.Error() value

See the following link for a list of valid formats:

https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Gov
  • 375
  • 1
  • 9
  • i got expected result when i using location "Asia/Calcutta".Is there is any other method for this by providing latitude and longitude of a location @Gov – farsana p b Jul 11 '17 at 07:33
  • There are a number of ways to find the data from lat/long: https://stackoverflow.com/questions/16086962/how-to-get-a-time-zone-from-a-location-using-latitude-and-longitude-coordinates – Gov Jul 11 '17 at 07:38
0

This is just converting UTC time string to your local time string according to your specified layout.

func UTCTimeStr2LocalTimeStr(ts, layout string) (string, error) {                                                                  
    timeObject, err := time.Parse(time.RFC3339, ts)
    if err != nil {
        return "", err
    }

    return time.Unix(timeObject.Unix(), 0).Format(layout), nil
}
lisprez
  • 71
  • 1
  • 6