In a previous attempt to parse timezone codes, the code below consistently yielded the result "[date] 05:00:00 0000 UTC" regardless of the timezone chosen for the parseAndPrint function.
// time testing with arbitrary format 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()) }
This issue stems from the fact that time.Parse interprets the time in the current location, which may not match the intended timezone.
To accurately parse timezone codes, the correct approach involves using time.Location. Here's an improved implementation:
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.UTC()) }
In this updated code:
The above is the detailed content of Why Does My Go Code Always Return UTC Time Despite Specifying Different Time Zones Using `time.Parse`?. For more information, please follow other related articles on the PHP Chinese website!