简体   繁体   中英

why does time.Parse parse the time incorrectly?

I'm trying to parse a string as time with but unfortunately go gets the wrong month (January instead of June)

package main

import "fmt"
import "time"

func main() {

    t := "2014-06-23T20:29:39.688+01:00"
    tc, _ := time.Parse("2006-01-02T15:04:05.000+01:00", t)
    
    fmt.Printf("t was %v and tc was %v", t, tc)

}

Play

The problem is that your timezone offset is ill-defined in the layout: the reference offset is -0700 . You defined yours as +01:00 , so the 01 is interpreted as the month and erase the previously defined one. And as your working offset is 01 as well, it is parsed as january.

The following example works for me playground

package main

import "fmt"
import "time"

func main() {

    t := "2014-06-23T20:29:39.688+01:00"
    tc, _ := time.Parse("2006-01-02T15:04:05.000-07:00", t)

    fmt.Printf("t was %v and tc was %v", t, tc)

}

Your layout string is incorrect. The numbers in the layout string have special meanings, and you are using 1 twice: once in the month portion and once in the time zone portion. The time zone in the string you are parsing is 01:00 , so you are storing 1 into the month. This explains why the returned month was January (the first month).

A corrected layout string is 2006-01-02T15:04:05.000-07:00 . Or, if you're happy with using Z to represent UTC, the time.RFC3339 constant might be appropriate.

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