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