Convert UTC to "local" time in Go

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

Solution 1:

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

Solution 2:

Your approach is flawed. A country can have several time zones, for example, US and Russia. Because of daylight saving time (DST), a time zone can have more than one time, for example, Hungary. Hungary is UTC +1:00 and is also UTC+2:00 for DST.

For each location that you want the local time for a given UTC time, use the IANA (tzdata) time zone location. For example,

package main

import (
    "fmt"
    "time"
)

func main() {
    utc := time.Now().UTC()
    fmt.Println(utc)
    local := utc
    location, err := time.LoadLocation("Europe/Budapest")
    if err == nil {
        local = local.In(location)
    }
    fmt.Println("UTC", utc.Format("15:04"), local.Location(), local.Format("15:04"))
    local = utc
    location, err = time.LoadLocation("America/Los_Angeles")
    if err == nil {
        local = local.In(location)
    }
    fmt.Println("UTC", utc.Format("15:04"), local.Location(), local.Format("15:04"))
}

Output:

2014-08-14 23:57:09.151377514 +0000 UTC
UTC 23:57 Europe/Budapest 01:57
UTC 23:57 America/Los_Angeles 16:57

References:

IANA Time Zone Database

tz database

tz database time zones

Time zone

Time in Hungary