0

I receive a JSON message coming from an API written in Go. One of the fields is a date, and it may be a time.Time{} that is turned into "0001-01-01T00:00:00Z" when creating the JSON.

On the receiving end, I will unmarshal the JSON message into a variable that matches the structure of the message, one of the field being the date one I mention above (of type time.Time).

I would like to check it against an empty one.

I expected that the code below would be OK, but it is not:

package main

import (
    "fmt"
    "time"
)

func main() {
    receivedDate := "0001-01-01T00:00:00Z"  // this mocks the content of the received field
    receivedDateParsed, _ := time.Parse(time.RFC3339, receivedDate) // this is equivlent to the unmarshalling into the message stricture
    if receivedDateParsed == time.Time{} {  // my comparison
        fmt.Print("date is empty")
    }
}

The error is Type 'time.Time' is not an expression but I am not sure what this means in the context of the time.Time{} I used.

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • the error you got there in particular is a parsing ambiguity that is solved by enclosing `time.Time{}` in brackets `()`. https://go.dev/play/p/zgEe6yEtorZ – blackgreen Apr 11 '22 at 12:21
  • 1
    And you should never use `==` on `time.Time` values, see [Why do 2 time structs with the same date and time return false when compared with ==?](https://stackoverflow.com/questions/36614921/why-do-2-time-structs-with-the-same-date-and-time-return-false-when-compared-wit/36615458#36615458); also see [Idiomatic way to represent optional time.Time in a struct](https://stackoverflow.com/questions/52216908/idiomatic-way-to-represent-optional-time-time-in-a-struct/52217049#52217049) – icza Apr 11 '22 at 12:23
  • 1
    [this](https://stackoverflow.com/questions/28447297/how-to-check-for-an-empty-struct/28447372#28447372) is an explanation of the parsing ambiguity. But as icza said, don't do that. The link is more for informative purposes. Use `IsZero` to check for empty dates – blackgreen Apr 11 '22 at 12:35

0 Answers0