繁体   English   中英

我无法在 Go 中解析日期/时间 - 杜松子酒

[英]I can not parse date/time in Go - Gin

我正在发送这个 json:

{"origin":{"lat":23.589367061768648,"lng":58.42860314995051},"destination":null,"vehicle":"WATER_TANKER_600GL","scheduled_time":"2022-07-27T14:16:00Z04:00"}

Golang Gin 处理器 function:

func (config *Config) CreateOrder(c *gin.Context) {

    userID := auth.GetToken(c).ID()

    data := &struct {
        Origin        models.Origin       `json:"origin" binding:"required"`
        Vehicle       VehicleType         `json:"vehicle" binding:"required"`
        Destination   *models.Destination `json:"destination" `
        ScheduledTime *time.Time          `json:"scheduled_time"`
    }{}

    if err := c.ShouldBindWith(data, binding.JSON); err != nil {
        fmt.Println(err) // -> prints the below error
        res.UnprocessableEntity(c, fmt.Sprintf("%s", err))
        return
    }

// rest of the code
}

我收到此错误:

parsing time "\"2022-07-27T14:16:00Z04:00\"" as "\"2006-01-02T15:04:05Z07:00\"": cannot parse "04:00\"" as "\""

请注意, JSON 没有定义日期或时间戳数据类型 将时间戳作为 JSON 字符串传输是可能的,但是如何解释或解释该时间戳字符串并不是一成不变的。 标准库( encoding/json包)支持解组time.Time值来自 JSON 字符串,但它要求它们遵守 RFC 3339 标准,否则解组将失败。

time.Time实现json.UnmarshalerTime.UnmarshalJSON()声明 JSON 字符串必须采用RFC 3339布局,即:

RFC3339 = "2006-01-02T15:04:05Z07:00"

布局中的Z表示:

数字时区偏移格式如下:

 "-0700" ±hhmm "-07:00" ±hh:mm "-07" ±hh

用 Z 替换格式中的符号会触发 ISO 8601 打印 Z 的行为,而不是 UTC 区域的偏移量。 因此:

 "Z0700" Z or ±hhmm "Z07:00" Z or ±hh:mm "Z07" Z or ±hh

这意味着如果时间有 UTC 偏移量,它应该是

"2022-07-27T14:16:00Z"

如果时间有+04:00时区,它应该是

"2022-07-27T14:16:00+04:00"

输入"2022-07-27T14:16:00Z04:00"对于 RFC 3339 无效。或者更改您的源以提供符合 RFC 3339 的时间戳字符串,或者如果您不能或不想这样做,您可以创建您的实现json.Unmarshaler的自定义类型,您自己处理这种非 RFC 3339 格式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM