admin管理员组

文章数量:1333381

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.toString());

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?

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.toString());

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?

Share asked Nov 19, 2009 at 3:00 SakthiSakthi 411 gold badge1 silver badge3 bronze badges 2
  • Possible duplicate: stackoverflow./questions/206384/how-to-format-json-date – mauris Commented Nov 19, 2009 at 3:23
  • @thephpdeveloper: I don't see how this is a dupe of that. This one has to do with calculating differences between dates, that one has to do with formatting a date. – Crescent Fresh Commented Nov 19, 2009 at 3:54
Add a ment  | 

2 Answers 2

Reset to default 3

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;

本文标签: How to get current UTC time in JSON format using JavascriptStack Overflow