"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Parse a Time String with a Specific Time Zone in Go?

How to Parse a Time String with a Specific Time Zone in Go?

Published on 2024-11-15
Browse:782

How to Parse a Time String with a Specific Time Zone in Go?

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:

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)
}

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:

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)
}

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.

Latest tutorial More>

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