2

I'm reading a timestamp from a file, and I assign the value to t:

t := "2016-11-02 19:23:05.503705739 +0000 UTC"

When I attempt to parse the string:

time, err := time.Parse("2016-11-02 19:18:57.149197306 +0000 UTC", t)

The result is:

0001-01-01 00:00:00 +0000 UTC

But I expected result to be:

"2016-11-02 19:18:57.149197306 +0000 UTC" ?

Please advise.

Mike
  • 1,884
  • 2
  • 24
  • 42
  • Was `err` nil? Gotta start by checking if `err == nil` and if false, what the contents of `err` are. – evanmcdonnal Nov 02 '16 at 19:34
  • err is parsing time "2016-11-02 19:35:35.173585795 +0000 UTC": month out of range – Mike Nov 02 '16 at 19:36
  • 1
    See: https://stackoverflow.com/questions/16536216/time-parse-behaviour, and https://stackoverflow.com/questions/31070301/time-parse-with-custom-layout, and https://stackoverflow.com/questions/18927725/strange-behavior-in-time-parse-function-in-go, and https://stackoverflow.com/questions/25845172/parsing-date-string-in-golang/25845327, etc... – JimB Nov 02 '16 at 19:41
  • I've read those @JimB ... evans explanation below helped a lot to clarify how the layout string is constructed – Mike Nov 02 '16 at 19:46

1 Answers1

3

You're not correctly providing the layout argument to Parse. You're supposed to be using Mon Jan 2 15:04:05 MST 2006 (this is magic value, you put create a string in the format you want but with that date) in the given format so in your case, it would be 2006-01-02 15:04:05.000000000 +0000 UTC plus the offset which I don't know off the top of my head for MST.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • This is what I was trying to understand regarding the format string. Let me give this a try and I will come back shortly – Mike Nov 02 '16 at 19:38
  • @Mike sounds good. That aspect of the time package is a little weird thought it's pretty easy to work with once you get used to it. I believe your offset would be `-7` btw. – evanmcdonnal Nov 02 '16 at 19:40
  • I'm still getting an error, I've uploaded the code here: https://play.golang.org/p/SPIMTX2jL4 – Mike Nov 02 '16 at 19:43
  • @Mike that's because your `layout` argument still had the 2016 date when it's supposed to be based on that epoch of Jan 2nd 2006. Here's a modified example that works; https://play.golang.org/p/QRrel6YSkC – evanmcdonnal Nov 02 '16 at 19:46
  • 2
    @Mike for that, your goal is to look at the format of your input time, then take that epoch (1/2/2006), and represent it in the format your input time is in. – evanmcdonnal Nov 02 '16 at 19:47