Converting UTC to Specific Time Zone in Go with time.LoadLocation
When converting UTC time to a specific local time, it's essential to consider time zone information for accuracy. Attempting to manually add time differences may result in incorrect results.
Instead, the preferred approach in Go is to use time.LoadLocation to obtain the time zone information for the desired location. Here's a corrected Go code 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) }
In this example, a map (countryTz) is used to associate country names with their corresponding time zone strings. The timeIn function takes the country name, loads the time zone information using time.LoadLocation, and returns the current time in that specific time zone.
The main function then prints the UTC time and the local times for Hungary and Egypt using timeIn. This approach ensures that differences in time zones and daylight savings are handled correctly.
The above is the detailed content of How to Accurately Convert UTC Time to a Specific Time Zone in Go?. For more information, please follow other related articles on the PHP Chinese website!