Home > Article > Backend Development > How to parse time string with time zone using Golang?
To parse time strings with time zones in Go, you can use the time package: use the time.Parse() function to parse time strings and specify the time format and string. For different time zones, use the time.ParseInLocation() function, specifying the format string, time string, and time zone location. To convert time zones, use the time.In() function, specifying the new time zone location. Practical analysis of API responses with time zones, using time.Parse() and the standard format time.RFC3339.
#How to use Golang to parse a time string with time zone?
In Golang, you can use the time
package to parse time strings with time zones. The following are the specific steps:
t, err := time.Parse("2006-01-02 15:04:05 MST", "2018-10-29 14:45:00 MST") if err != nil { log.Fatal(err) }
time.Parse ()
The function takes two parameters: time format string and time string. In order to parse time strings with different time zones, you can use time.ParseInLocation()
Function:
loc, err := time.LoadLocation("America/Los_Angeles") if err != nil { log.Fatal(err) } t, err := time.ParseInLocation("2006-01-02 15:04:05", "2018-10-29 14:45:00", loc) if err != nil { log.Fatal(err) }
time.ParseInLocation()
The function takes three parameters: time format string, time string and a time zone Location. time.LoadLocation()
function. If you need to convert the parsed time to a different time zone, you can use time. In()
Function:
loc, err := time.LoadLocation("America/New_York") if err != nil { log.Fatal(err) } t = t.In(loc)
time.In()
The function takes a time zone location as a parameter and returns a time converted to that time zone. Practical case: Parsing API responses with time zones
Consider a scenario where a time string with time zones is obtained from an API response. The string is in the following format:
2018-10-29T14:45:00Z
To parse this time string:
t, err := time.Parse(time.RFC3339, "2018-10-29T14:45:00Z") if err != nil { log.Fatal(err) }
time.RFC3339
is a standard time format that represents a date and time with a time zone.
The above is the detailed content of How to parse time string with time zone using Golang?. For more information, please follow other related articles on the PHP Chinese website!