3

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
The user with no hat
  • 10,166
  • 20
  • 57
  • 80

2 Answers2

13

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)

}
Elwinar
  • 9,103
  • 32
  • 40
  • if I change 2006 to 2003, it failed to parse again. Why? https://play.golang.org/p/mv8kD63O4k – Zhe Hu Jun 28 '16 at 19:51
  • 2
    Because the string for year is `2006`. – Elwinar Jun 29 '16 at 07:50
  • Yeah you really have to use this specific date to specify the date string's format. It's a bit wonky, I think `YYYY` etc make formatting less clunky and error prone, but that's how it is. – Pierre Jul 02 '20 at 07:10
5

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.

OmarOthman
  • 1,718
  • 2
  • 19
  • 36
James Henstridge
  • 42,244
  • 6
  • 132
  • 114