jquery - How do I format a Microsoft JSON date?

ID : 414

viewed : 222

Tags : jqueryasp.netajaxjsonjquery





Top 5 Answer for jquery - How do I format a Microsoft JSON date?

vote vote

95

eval() is not necessary. This will work fine:

var date = new Date(parseInt(jsonDate.substr(6))); 

The substr() function takes out the /Date( part, and the parseInt() function gets the integer and ignores the )/ at the end. The resulting number is passed into the Date constructor.


I have intentionally left out the radix (the 2nd argument to parseInt); see my comment below.

Also, I completely agree with Rory's comment: ISO-8601 dates are preferred over this old format - so this format generally shouldn't be used for new development.

For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:

var date = new Date(jsonDate); //no ugly parsing needed; full timezone support 
vote vote

85

You can use this to get a date from JSON:

var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)")); 

And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.

vote vote

70

For those using Newtonsoft Json.NET, read up on how to do it via Native JSON in IE8, Firefox 3.5 plus Json.NET.

Also the documentation on changing the format of dates written by Json.NET is useful: Serializing Dates with Json.NET

For those that are too lazy, here are the quick steps. As JSON has a loose DateTime implementation, you need to use the IsoDateTimeConverter(). Note that since Json.NET 4.5 the default date format is ISO so the code below isn't needed.

string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter()); 

The JSON will come through as

"fieldName": "2009-04-12T20:44:55" 

Finally, some JavaScript to convert the ISO date to a JavaScript date:

function isoDateReviver(value) {   if (typeof value === 'string') {     var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(?:([\+-])(\d{2})\:(\d{2}))?Z?$/.exec(value);       if (a) {         var utcMilliseconds = Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);         return new Date(utcMilliseconds);       }   }   return value; } 

I used it like this

$("<span />").text(isoDateReviver(item.fieldName).toLocaleString()).appendTo("#" + divName); 
vote vote

68

The original example:

/Date(1224043200000)/   

does not reflect the formatting used by WCF when sending dates via WCF REST using the built-in JSON serialization. (at least on .NET 3.5, SP1)

I found the answer here helpful, but a slight edit to the regex is required, as it appears that the timezone GMT offset is being appended onto the number returned (since 1970) in WCF JSON.

In a WCF service I have:

[OperationContract] [WebInvoke(     RequestFormat = WebMessageFormat.Json,     ResponseFormat = WebMessageFormat.Json,     BodyStyle = WebMessageBodyStyle.WrappedRequest     )] ApptVisitLinkInfo GetCurrentLinkInfo( int appointmentsId ); 

ApptVisitLinkInfo is defined simply:

public class ApptVisitLinkInfo {     string Field1 { get; set; }     DateTime Field2 { get; set; }     ... } 

When "Field2" is returned as Json from the service the value is:

/Date(1224043200000-0600)/ 

Notice the timezone offset included as part of the value.

The modified regex:

/\/Date\((.*?)\)\//gi 

It's slightly more eager and grabs everything between the parens, not just the first number. The resulting time sinze 1970, plus timezone offset can all be fed into the eval to get a date object.

The resulting line of JavaScript for the replace is:

replace(/\/Date\((.*?)\)\//gi, "new Date($1)"); 
vote vote

60

Don't repeat yourself - automate date conversion using $.parseJSON()

Answers to your post provide manual date conversion to JavaScript dates. I've extended jQuery's $.parseJSON() just a little bit, so it's able to automatically parse dates when you instruct it to. It processes ASP.NET formatted dates (/Date(12348721342)/) as well as ISO formatted dates (2010-01-01T12.34.56.789Z) that are supported by native JSON functions in browsers (and libraries like json2.js).

Anyway. If you don't want to repeat your date conversion code over and over again I suggest you read this blog post and get the code that will make your life a little easier.

Top 3 video Explaining jquery - How do I format a Microsoft JSON date?







Related QUESTION?