如何将解析的日期与空日期进行比较?[复制]

How can I compare a parsed date to an empty date? [duplicate]

提问人:WoJ 提问时间:4/11/2022 更新时间:4/11/2022 访问量:459

问:

我收到一条来自用 Go 编写的 API 的 JSON 消息。其中一个字段是日期,它可能是创建 JSON 时转换为的字段。time.Time{}"0001-01-01T00:00:00Z"

在接收端,我将把JSON消息解组到一个与消息结构匹配的变量中,其中一个字段是我上面提到的日期(类型)。time.Time

我想对照一个空的检查它。

我期望下面的代码没问题,但事实并非如此:

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")
    }
}

错误是,但我不确定这在我使用的上下文中意味着什么。Type 'time.Time' is not an expressiontime.Time{}

日期比较

评论

0赞 blackgreen 4/11/2022
您在那里遇到的错误是解析歧义,可以通过括在括号中来解决。go.dev/play/p/zgEe6yEtorZtime.Time{}()
1赞 icza 4/11/2022
而且你永远不应该使用 on 值,参见为什么 2 个具有相同日期和时间的时间结构与 == 相比返回 false?;另请参阅表示可选时间的惯用方式。结构中的时间==time.Time
1赞 blackgreen 4/11/2022
这是对解析歧义的解释。但正如 icza 所说,不要那样做。该链接更多用于提供信息。用于检查空日期IsZero

答: 暂无答案