简体   繁体   中英

Error while using time.Parse when timezone and offset are together

I have the following code :

package main

import (
    "fmt"
    "time"
    "log"
)

func main() {
    date, err := time.Parse("Monday, 2 January 2006 15:04:05 PM MST-07:00" ,"Thursday, 17 August 2020 13:20:00 PM GMT+08:00")
    if err != nil {
      log.Fatal(err.Error())
    }
    fmt.Println(date)
}

And it fails with the following error :

2009/11/10 23:00:00 parsing time "Thursday, 17 August 2020 13:20:00 PM GMT+08:00" as "Monday, 2 January 2006 15:04:05 PM MST-07:00": cannot parse ":00" as "-07:00"

But it succeeds if I separate MST-07:00 with a space as : "MST -07:00" in both layout sample and actual string.

What am I doing wrong?

GMT times undergo special handling by time.Parse . The signed offset for GMT in the value must be in the range -23 through +23 excluding zero, and may not include a colon. The layout should just specify MST without an offset.

For example:

package main

import (
    "fmt"
    "log"
    "time"
)

func main() {
    for _, ts := range []string{
        "Thursday, 17 August 2020 13:20:00 PM GMT",
        "Thursday, 17 August 2020 13:20:00 PM GMT+2",
        "Thursday, 17 August 2020 13:20:00 PM GMT-2",
    } {
        date, err := time.Parse("Monday, 2 January 2006 15:04:05 PM MST", ts)
        if err != nil {
            log.Fatal(err.Error())
        }
        fmt.Println(date)
    }
}

yields the output:

crow@mac:tp$ ./example
2020-08-17 13:20:00 +0000 GMT
2020-08-17 15:20:00 +0200 GMT+2
2020-08-17 11:20:00 -0200 GMT-2

An issue was raised for this a while back, and the outcome was (with reference to an example time string containing GMT+10:00 ):

The special handling of GMT, which is needed for other things, makes it very difficult to know whether the +10:00 should be considered part of the time zone or left alone to match the layout.

and so the issue was closed without proposed changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM