当我在js中这样定义时间
{expiry:new Date()}
并像这样在 go endpoints 中创建一个结构
{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 \"\"\""
有什么建议吗?
最佳答案
time.UnmarshalJSON 的文档指出:
UnmarshalJSON implements the json.Unmarshaler interface. The time is expected to be a quoted string in RFC 3339 format.
存在一个问题,即并非所有浏览器都必须将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"}
关于javascript - 我怎样才能使 go Time 与 js Date 兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20985553/