DCSIMG
Quick Tip – Converting JSON Serialized .NET DateTime to JavaScript Date - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2012 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

Quick Tip – Converting JSON Serialized .NET DateTime to JavaScript Date

Quick Tip – Converting JSON Serialized .NET DateTime to JavaScript Date

When you are using the controller JSON method in ASP.NET MVC or scriptable WCF services you sometimes have to serialize a .NET DateTime property. The DataContractJsonSerializer will serialize it into the following format:

/Date(1235398665390)/ 

This format indicate to the client side parsers that the data fragment that was sent is a date representation.
But how can you convert it to a JavaScript Date object?

There are a few methods:

  • “Brutal Force”: Extract the number using regular expression or substring functions and pass it to the Date object which get the time in milliseconds in its constructor:
    var date = new Date(1235398665390);
  • Server Side Approach: Send to the client side not a .NET DateTime but the total milliseconds and then use the same constructor from the previous bullet. You should pay attention that JavaScript’s base date is 1/1/1970. The following code can help:
    var baseDate = new DateTime(1970, 1, 1); 
    var currentDate = DateTime.Now.ToUniversalTime(); 
    TimeSpan ts = new TimeSpan(dcurrentDate.Ticks - baseDate.Ticks); 
    return ts.TotalMilliseconds;
  • The Eval Way: on the client side use the eval function to evaluate and create the Date object:
    var date = eval("new " + dateFromTheServer.slice(1, -1));

    Where the dateFromTheServer is in the format which was presented at the top of the post.

There are probably other ways which can help you. What is your way?

Comments

Paul Delcogliano said:

Hi Gil,

On the client-side, I use code like this to create the date object...

var d = new Date(parseInt(valueToFormat.substr(6)));

where valueToFormat is in the format at the top of your post.

Paul

# October 17, 2011 7:07 PM