Using Time Zones Correctly in Go
When attempting to parse timezone codes, it's crucial to understand the nuances of how timezones are handled in Go.
The code you provided sets up a function called parseAndPrint that takes a time instance and a timezone abbreviation as arguments. However, regardless of the timezone you specify, the output of the function is always "05:00:00 0000 UTC."
The issue arises because you are parsing the time in your current location, which may differ from the desired timezone. Go's time.Parse function assumes you are parsing in the current location unless explicitly specified using a time.Location.
To correctly parse a time in a specific timezone, you should use the following steps:
Here is an example of how you could use these steps in your code:
func parseAndPrintWithLocation(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", fmt.Sprintf("05:00:00", timezone), location) 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) }
By utilizing the correct approach with timezone locations, you can ensure that theparsed time reflects the desired timezone, allowing your code to handle times from different regions accurately.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3