How to get current UTC time in JSON format using Javascript?
I have a JSON Date for example: "/Date(1258529233000)/"
I got below code to convert this JSON date to UTC Date in String Format.
var s = "\\/Date(1258529233000)\\/";
s = s.slice(7, 20);
var n = parseInt(s);
var d = new Date(n);
alert(d.toStr开发者_开发知识库ing());
Now I need to get current UTC Date with Time and convert it into JSON date format.
Then do a date difference between these two dates and get number of minutes difference.
Can someone help me with this?
javascript Date objects are all UTC Dates until you convert them to strings.
Date.fromJsnMsec= function(jsn){
jsn= jsn.match(/\d+/);
return new Date(+jsn)
}
Date.prototype.toJsnMsec= function(){
return '/Date('+this.getTime()+')/';
}
//test
var s= "\/Date(1258529233000)\/";
var D1= Date.fromJsnMsec(s);
var D2= new Date();
var diff= Math.abs(D1-D2)/60000;
var string= diff.toFixed(2)+' minutes between\n\t'+
D1.toUTCString()+' and\n\t'+D2.toUTCString()+'\n\n'+s+', '+D2.toJsnMsec();
alert(string)
The best way to do this in modern JS implementations is simple:
var now = (new Date()).toJSON();
This was standardized in EMCAScript 5.1. If you need to support older browsers, you can do a long-form version (including something like json2.js if needed):
var now = JSON.parse(JSON.stringify({now: new Date()})).now;
精彩评论