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) }
UTC() function in Go language is used to yield “t” with the location that is set to UTC. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
UTC time in ISO-8601 is 14:19:11Z.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With