Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) } 
like image 623
hey Avatar asked Aug 14 '14 21:08

hey


People also ask

What is UTC Golang?

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.

What is UTC time now in 24 hour format?

UTC time in ISO-8601 is 14:19:11Z.


1 Answers

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) } 
like image 118
OneOfOne Avatar answered Oct 02 '22 19:10

OneOfOne