如何将解析的日期与空日期进行比较?

发布于 2025-01-20 15:06:29 字数 794 浏览 2 评论 0原文

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

在接收端,我会将 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 expression 但我不确定这在 的上下文中意味着什么我使用的>time.Time{}

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文