Home >Backend Development >Golang >Why Does Go\'s `time.Parse()` Misinterpret Timezone Identifiers and How Can I Fix It?
When parsing a time string, Go's time.Parse() attempts to interpret any included timezone identifier based on the current location. If the timezone is unknown, Parse() assumes it's in a fabricated location with the given abbreviation and zero offset.
Consider the following code snippet:
const format = "2006 01 02 15:04 MST" date := "2018 08 01 12:00 EDT" tn, _ := time.Parse(format, date)
Here, we define a layout format and parse a date string that includes the timezone identifier "EDT". However, when we print the parsed time, we get:
2018-08-01 12:00:00 +0000 EDT
Notice that the time zone is shown as " 0000 EDT" despite EDT being a daylight savings time zone with an offset of -0400 from UTC.
This happens because Parse() relies on the current system location, which might not recognize the "EDT" abbreviation. Instead, it interprets it as an unknown zone and assigns a zero offset.
To avoid this issue, we can either:
const format = "2006 01 02 15:04 -0400" tn, _ := time.Parse(format, date)
aloc, _ := time.LoadLocation("America/New_York") tn, _ := time.ParseInLocation(format, date, aloc)
By using these techniques, we ensure that the timezone information is correctly interpreted and the parsed time reflects the intended offset accurately.
The above is the detailed content of Why Does Go\'s `time.Parse()` Misinterpret Timezone Identifiers and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!