我有一个用户创建的日期对象,时区由浏览器填写,如下所示:
var date = new Date(2011, 05, 07, 04, 0, 0);
> Tue Jun 07 2011 04:00:00 GMT+1000 (E. Australia Standard Time)
不过,当我将其字符串化时,时区会再见
JSON.stringify(date);
> "2011-06-06T18:00:00.000Z"
在保留浏览器时区的同时获取 ISO8601 字符串的最佳方法是使用 moment.js 和 moment.format()
,但如果我是通过内部使用 JSON.stringify
的东西(在本例中为 AngularJS)序列化整个命令
var command = { time: date, contents: 'foo' };
$http.post('/Notes/Add', command);
为了完整起见,我的域确实需要本地时间和偏移量。
最佳答案
假设您有某种包含 Date
的对象:
var o = { d : new Date() };
您可以覆盖 Date
原型(prototype)的 toJSON
函数。这里我使用 moment.js 从日期创建一个 moment
对象,然后使用 moment 的不带参数的 format
函数,它发出包含偏移量的 ISO8601 扩展格式。
Date.prototype.toJSON = function(){ return moment(this).format(); }
现在当您序列化对象时,它将使用您要求的日期格式:
var json = JSON.stringify(o); // '{"d":"2015-06-28T13:51:13-07:00"}'
当然,这会影响 所有 Date
对象。如果您只想更改特定日期对象的行为,您可以只覆盖该特定对象的 toJSON
函数,如下所示:
o.d.toJSON = function(){ return moment(this).format(); }
https://stackoverflow.com/questions/31096130/