-1

I have a string that has a timestamp in the format

"2021-02-04 23:45:00" but when I try and parse this with time.parse it seemingly cuts off the year part.

The code is

case "period_end":
                fmt.Println(record[i])
                ts, err := time.Parse("2021-02-04 23:45:00", record[i])
                if err != nil {
                    log.Printf("Time conversion failed: %v", err)
                    return
                }
reading.Interval = t

where record[i] at this point is a string with

2021-02-04 00:15:00

and reading.Interval is time.Time

The error returned in the Printf is

Time conversion failed: parsing time "2021-02-04 00:15:00" as "2021-02-04 23:45:00": cannot parse "-02-04 00:15:00" as "1"

which I can't find in any search I've done. What am I missing here?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Peter Nunn
  • 2,110
  • 3
  • 29
  • 44

2 Answers2

2

Replace the first parameter in time.Parse:

from

"2021-02-04 23:45:00"

to

"2006-01-02 15:04:00"

Golang uses a specific date for formatting, no idea why https://golang.org/src/time/format.go

CodeNinja
  • 616
  • 4
  • 18
1

Go uses this default time for setting up the layout:

"2006-01-02T15:04:05.000Z"

More info for this layout:

The reference time used in the layouts is the specific time:

Mon Jan 2 15:04:05 MST 2006

which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be thought of as

01/02 03:04:05PM '06 -0700

So to solve your problem:

package main

import (
    "fmt"
    "time"
)

func main() {
    recordTime := "2021-02-04 23:45:00"
    ts, err := time.Parse("2006-01-02 15:04:05", recordTime)
        if err != nil {
            fmt.Println("error: ", err)
        return
    }
    fmt.Println(ts)
}

This code can be found here.

Pallav Jha
  • 3,409
  • 3
  • 29
  • 52