0

I am trying to just trying to parse a datetime that I get from my collection.

The query

createdBefore := c.QueryParam("createdBefore")
if createdBefore != "" {

    // inside database it contains "createdAt"
    // "createdAt" : ISODate("2020-11-05T10:03:43.452Z")
    datetimer, err := time.Parse("2020-11-05T10:03:43.452Z", createdBefore)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(datetimer)

}

The error:

parsing time "2021-11-01T08:23:41.502Z" as "2020-11-05T10:03:43.452Z": cannot parse "-11-01T08:23:41.502Z" as "0-"
0001-01-01 00:00:00 +0000 UTC
John
  • 47
  • 1
  • 8
  • Use the layout string `"2006-01-02T15:04:5.000Z"`. And read the docs. And try to search for your problem before you post a question, there are numerous questions about parsing time in Go. Also the mongo drivers hand you `time.Time` values, it's not necessary to do this yourself. – icza Nov 05 '20 at 10:20
  • so should my struct be of type time.Time? – John Nov 05 '20 at 10:28
  • For querying date/time values, use `time.Time` in your struct. The driver will automatically parse the time. (Unless the field in your document is not a date but a string.) – icza Nov 05 '20 at 10:33
  • Reason I ask is when I try your solution I get: parsing time "2012-11-05 10:29:52.465Z" as "2006-01-02T15:04:5.000Z": cannot parse " 10:29:52.465Z" as "T" 0001-01-01 00:00:00 +0000 UTC – John Nov 05 '20 at 10:37
  • In your question you have a time `"2021-11-01T08:23:41.502Z"` with a **T** in the middle, so I provided you a layout string with a **T** in the middle. In your last comment there is no **T** but a space in the middle. So adjust the layout string to that. And please read the docs, this is explained in the doc of `time.Parse()`. It's better to understand it than to rely on someone else's answer for every micro-change. – icza Nov 05 '20 at 10:54

0 Answers0