Convert UTC to Local Time in Go with Precision
Question:
In an attempt to convert UTC time to local time for specific countries, a Go program encounters incorrect results despite considering the UTC difference. What could be the underlying issue?
Answer:
The error arises when the time is being calculated by manually adding the UTC difference as a duration. This approach does not account for other factors, such as daylight saving time (DST).
To accurately convert UTC time to local time, the correct method is to use time.LoadLocation. Here's how you can do it:
import "time" // A map of country names to their time zone names var countryTz = map[string]string{ "Hungary": "Europe/Budapest", "Egypt": "Africa/Cairo", } // Function to convert UTC time to the local time of a specific country func timeIn(name string) time.Time { loc, err := time.LoadLocation(countryTz[name]) if err != nil { panic(err) } return time.Now().In(loc) } // Example usage 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) }
This code first defines a mapping of country names to their corresponding time zone names. Then, time.LoadLocation is used to obtain the specific time zone for a given country. By calling time.Now().In(loc), the current UTC time is converted to the local time for the desired country, taking into account DST and other factors.
The above is the detailed content of Why Does Manually Adding UTC Offset Fail to Accurately Convert UTC to Local Time in Go?. For more information, please follow other related articles on the PHP Chinese website!