如何使Go的时间兼容JavaScript的Date对象?

huangapple go评论117阅读模式
英文:

How can I make go Time compatible with js Date

问题

当我在JavaScript中这样定义时间:

{expiry:new Date()}

并且在Go的端点中创建一个结构体,如下所示:

{Expiry time.Time `json:"expiry"`}

我会从Go中得到一个解析错误:

"parsing time \"\"2006-01-02T15:04:05Z07:00\"\" as \"\"2006-01-02T15:04:05Z07:00\"\": cannot parse \"07:00\" as \"\"\""

有什么建议吗?

英文:

When I define time like this in js

{expiry:new Date()}

and create a struct in go endpoints like this

{Expiry time.Time `json:"expiry"`}

I get a parse error from go

"parsing time \"\"2006-01-02T15:04:05Z07:00\"\" as \"\"2006-01-02T15:04:05Z07:00\"\": cannot parse \"07:00\"\" as \"\"\""

Any suggestions?

答案1

得分: 8

time.UnmarshalJSON的文档说明如下:

UnmarshalJSON实现了json.Unmarshaler接口。时间应该是一个以RFC 3339格式引用的字符串。

存在一个问题,即并非所有浏览器都将DateTime对象编码为RFC3339格式。然而,您的错误消息似乎并未暗示这一点。您似乎尝试编码以下JSON字符串:

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

这不是一个时间戳,而是time包的参考布局。请参阅这个Playground示例,展示了Go语言对时间戳的期望格式:http://play.golang.org/p/4NQ1pRidPt

然而,浏览器的不一致性仍然存在问题。为了避免这个问题,您可以使用一个函数或库,就像@elithrar建议的那样:

var a = {expiry: moment(new Date()).format("YYYY-MM-DDTHH:mm:ssZ")};
console.log(a);

输出:

{"expiry": "2014-01-08T08:54:44+01:00"}

JSFiddle

英文:

The documentation for time.UnmarshalJSON states:

>UnmarshalJSON implements the json.Unmarshaler interface. The time is expected to be a quoted string in RFC 3339 format.

There is a problem that all browsers doesn't necessarily encode DateTime objects into RFC3339 format. However, your error message doesn't seem to imply that. You seem to try to encode the following JSON string:

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

That is not a timestamp, but rather the time package's reference layout. See this Playground example that shows how Go expects a timestamp to be like: http://play.golang.org/p/4NQ1pRidPt

However, there is still that problem with browser inconsistency. To avoid this you can use a function or library, as @elithrar suggested:

var a = {expiry: moment(new Date()).format("YYYY-MM-DDTHH:mm:ssZ")};
console.log(a);

Output:

{"expiry": "2014-01-08T08:54:44+01:00"} 

JSFiddle

huangapple
  • 本文由 发表于 2014年1月8日 09:49:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/20985553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定