Understanding Time Zone Parsing in Go
Parsing time zone codes in Go involves converting a string representation of a time zone into a corresponding *time.Location object. However, in certain scenarios, the parsed result may not accurately reflect the desired time zone. This article explores a common issue in time zone parsing and provides solutions.
Problem Formulation
Consider the following code:
package main import ( "fmt" "time" ) func main() { now := time.Now() parseAndPrint(now, "BRT") parseAndPrint(now, "EDT") parseAndPrint(now, "UTC") } func parseAndPrint(now time.Time, timezone string) { test, err := time.Parse("15:04:05 MST", fmt.Sprintf("05:00:00 %s", timezone)) if err != nil { fmt.Println(err) return } test = time.Date( now.Year(), now.Month(), now.Day(), test.Hour(), test.Minute(), test.Second(), test.Nanosecond(), test.Location(), ) fmt.Println(test.UTC()) }
When running this code, the output always shows "[date] 05:00:00 0000 UTC", regardless of the specified time zone. This is because the code is parsing the time in the current location and then setting the time zone explicitly to UTC.
Solution: Using time.Location
To correctly handle time zone parsing, we need to use the *time.Location type. We can load a location from the local timezone database using time.LoadLocation and then parse the time using time.ParseInLocation. Here's the modified code:
package main import ( "fmt" "time" ) func main() { now := time.Now() parseAndPrint(now, "BRT") parseAndPrint(now, "EDT") parseAndPrint(now, "UTC") } func parseAndPrint(now time.Time, timezone string) { location, err := time.LoadLocation(timezone) if err != nil { fmt.Println(err) return } test, err := time.ParseInLocation("15:04:05 MST", "05:00:00", location) if err != nil { fmt.Println(err) return } fmt.Println(test) }
Now, the code will correctly parse the time zone specific time and print the result in the desired time zone format.
The above is the detailed content of Why Does Go\'s `time.Parse` Fail to Accurately Parse Time Zones, and How Can This Be Fixed?. For more information, please follow other related articles on the PHP Chinese website!