Parsing Time with a Specific Time Zone
You can use time.ParseTime() to get a time struct from a string. It takes a layout string as an argument, which specifies the format of the input string. The layout string must match the format of the input string exactly.
If you need to parse a time string that includes a time zone, you can use time.ParseInLocation(). This function takes a layout string and a location as arguments. The location can be a time.Location value or a string representing a time zone name.
For example, the following code parses a time string that includes a time zone:
<code class="go">import ( "fmt" "time" ) func main() { const layout = "2006-01-02 15:04" const timeStr = "2012-07-09 05:02:00 +0000 CEST" t, err := time.ParseInLocation(layout, timeStr, time.Local) if err != nil { fmt.Println(err) return } fmt.Println(t) }</code>
This code will print the following output:
2012-07-09 05:02:00 +0000 CEST
The time.ParseInLocation() function will parse the time string according to the layout string and the specified location. In this case, the layout string is "2006-01-02 15:04" and the location is "CEST". The time.ParseInLocation() function will return a time.Time value that represents the parsed time.
If you do not specify a location, the time.ParseInLocation() function will use the local time zone. This means that the parsed time will be converted to the local time zone.
You can avoid this by creating a time.Time value with the correct time and time zone:
<code class="go">import ( "fmt" "time" ) func main() { const layout = "2006-01-02 15:04" const timeStr = "2012-07-09 05:02:00" const timeZone = "CEST" pz, err := time.LoadLocation(timeZone) if err != nil { fmt.Println(err) return } t, err := time.Parse(layout, timeStr) if err != nil { fmt.Println(err) return } T := t.In(pz) fmt.Println(T) }</code>
This code will print the following output:
2012-07-09 05:02:00 +0200 CEST
The output of this code shows the time in the correct time zone.
The above is the detailed content of How to Parse a Time String with a Specific Time Zone in Go?. For more information, please follow other related articles on the PHP Chinese website!