如何JSON引用JavaScript日期并保留时区 [英] How to JSON stringify a javascript Date and preserve timezone
问题描述
var date = new Date(2011,05,07,04,0,0);
> 2011年5月17日04:00:00 GMT + 1000(E.澳大利亚标准时间)
当我但是,这个时区是跟着再见的。
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',命令);
为了完整,我的域 需要本地时间和偏移量
假设您有某种对象包含 Date
:
var o = {d:new Date()};
您可以覆盖 toJSON
日期
原型。在这里,我使用moment.js从日期创建一个时刻
对象,然后使用时刻的格式
函数,不带参数,发出ISO8601扩展格式,包括偏移量。
Date.prototype.toJSON = function(){return moment(this).format (); }
现在,当序列化对象时,它将使用您要求的日期格式:
var json = JSON.stringify(o); //'{d:2015-06-28T13:51:13-07:00}'
当然,这将影响 Date
对象。如果要更改仅特定日期对象的行为,可以仅覆盖特定对象的 toJSON
函数,如下所示:
odtoJSON = function(){return moment(this).format(); }
I have a date object that's created by the user, with the timezone filled in by the browser, like so:
var date = new Date(2011, 05, 07, 04, 0, 0);
> Tue Jun 07 2011 04:00:00 GMT+1000 (E. Australia Standard Time)
When I stringify it, though, the timezone goes bye-bye
JSON.stringify(date);
> "2011-06-06T18:00:00.000Z"
The best way I can get a ISO8601 string while preserving the browser's timezone is by using moment.js and using moment.format()
, but of course that won't work if I'm serializing a whole command via something that uses JSON.stringify
internally (in this case, AngularJS)
var command = { time: date, contents: 'foo' };
$http.post('/Notes/Add', command);
For completeness, my domain does need both the local time and the offset.
Assuming you have some kind of object that contains a Date
:
var o = { d : new Date() };
You can override the toJSON
function of the Date
prototype. Here I use moment.js to create a moment
object from the date, then use moment's format
function without parameters, which emits the ISO8601 extended format including the offset.
Date.prototype.toJSON = function(){ return moment(this).format(); }
Now when you serialize the object, it will use the date format you asked for:
var json = JSON.stringify(o); // '{"d":"2015-06-28T13:51:13-07:00"}'
Of course, that will affect all Date
objects. If you want to change the behavior of only the specific date object, you can override just that particular object's toJSON
function, like this:
o.d.toJSON = function(){ return moment(this).format(); }
这篇关于如何JSON引用JavaScript日期并保留时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!