Convert UTC to Local Time in Go: Troubleshooting Incorrect Results
When converting UTC to local time, it's important to consider time zone differences and the correct method for performing the conversion.
In the provided code snippet, the attempt to manually add the time zone offset as a duration to the current UTC time can lead to incorrect results due to factors such as daylight saving time.
Time Zone Mapping:
The code relies on a static map to store time zone offsets. A more reliable approach involves using the time.LoadLocation function, which dynamically loads time zone information based on the specified name. This ensures the accuracy of time zone differences.
In-Built Time Zone Conversion:
Instead of manually adjusting the time, it's recommended to utilize the time.In method, which converts the timestamp to a specific time zone. This takes into account the current settings and daylight saving time adjustments, providing more accurate results.
Code示例:
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) }
By using time.LoadLocation and time.In, this revised code ensures that the local time is correctly converted from UTC, taking into account time zone differences and daylight saving time.
The above is the detailed content of Why Does Manually Converting UTC to Local Time in Go Often Produce Incorrect Results?. For more information, please follow other related articles on the PHP Chinese website!