Convert UTC to "local" time in Go

hey picture hey · Aug 14, 2014 · Viewed 50.6k times · Source

How can I convert UTC time to local time?

I've created a map with the UTC difference for all the countries I need the local time. Then I add that difference as duration to the current time (UTC) and print the result hoping that's the local time of that specific country.

For some reasons the result is wrong. For example with Hungary there is one hour difference. Any idea why I'm getting incorrect results?

package main

import "fmt"
import "time"

func main() {

    m := make(map[string]string)
    m["Hungary"] = "+01.00h"

    offSet, err := time.ParseDuration(m["Hungary"])
    if err != nil {
        panic(err)
    }
    t := time.Now().UTC().Add(offSet)
    nice := t.Format("15:04")

    fmt.Println(nice)
}

Answer

OneOfOne picture OneOfOne · Aug 15, 2014

Keep in mind that the playground has the time set to 2009-11-10 23:00:00 +0000 UTC, so it is working.

The proper way is to use time.LoadLocation though, here's an example:

var countryTz = map[string]string{
    "Hungary": "Europe/Budapest",
    "Egypt":   "Africa/Cairo",
}

func timeIn(name string) time.Time {
    loc, err := time.LoadLocation(countryTz[name])
    if err != nil {
        panic(err)
    }
    return time.Now().In(loc)
}

func main() {
    utc := time.Now().UTC().Format("15:04")
    hun := timeIn("Hungary").Format("15:04")
    eg := timeIn("Egypt").Format("15:04")
    fmt.Println(utc, hun, eg)
}