Converting UTC time to local time can be a challenge, especially when considering time zone variations. In Go, some users have encountered incorrect results when attempting to add UTC time offset durations to the current time.
The issue lies in the handling of time zones. While adding the time offset duration can adjust the time value, it does not account for the specific time zone's rules and DST (Daylight Saving Time) changes. To accurately convert UTC to local time, the proper way is to use the time.LoadLocation function.
The following code demonstrates how to use time.LoadLocation to obtain local time in specific locations:
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, countryTz defines a map of countries and their corresponding time zone names. The timeIn function loads the appropriate time zone and converts the current time to the local time in that time zone.
By using time.LoadLocation, the code ensures that time zone rules and DST adjustments are taken into account, providing accurate local times.
The above is the detailed content of How to Accurately Convert UTC to Local Time in Go?. For more information, please follow other related articles on the PHP Chinese website!