I hate those @#! JavaScript dates

I actually already posted about this very same thing before. But I’m trying to allow myself to be a little more expressive and descriptive in my posts, so consider this a makeover. Thanks:

Ok so maybe the title to this post is a little harsh. But I only say it because I love JSON and jQuery so much. With a simple $.post() and an ASP.NET MVC service things just work. Things except of course for those @#! dates.

If you haven’t experience this. JSON notation looks a lot like JavaScript, it’s super simple, it make XML look like a math problem at MIT.

XML: <Person><Name>John Doe</Name><Age>45</Age></Person>

JSON: { "Name": "John Doe", "Age": 45 }

That’s great and best of all it just works. If you do a post and the service returns JSON the post will return an object.

var test = { "Name": "John Doe", "Age": 45 };

$.post("MyService", function (person) {
    alert("Hello " + person.Name);
});

Beautiful, just beautiful. The string is a string. The number is a number. And the date is a… string? Yep it’s a string in the format "/Date(23947298342)/". Now there are whole bunch of reasons why that is, but at the end of the day I just wanted a date object.

So what’s a guy to do? Create a library of course! I attached it to this email.

Just include jquery.DateTime.js right after you include jQuery. Should look something like this:

<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.DateTime.js" type="text/javascript"></script>

Here’s how it works: Turns out jQuery has a collection of ‘converters’ that it uses depending on the kind of data it’s trying to parse. So I simply replaced the default converter for JSON with my own.

The default converter just called $.parseJSON() and so does mine with one difference, in mine after I parse it into an object I use reflection to enumerate through all the properties of the object generated by $parseJSON() whenever it finds a string matching the date format it converts it into a JavaScript date.

The conversion itself is actually very simple just parse out the number in the string and pass it as the parameter to new Date().

Now that what you get is an actual date you can perform all the regular JavaScript date operations. And you can dynamically format the date however you like using libraries like Steven Levithan’s dateFormat() which you can find here:

http://blog.stevenlevithan.com/archives/date-time-format

P.S. Note the issue wasn’t really JavaScript it’s actually ASP.NET “issue”. There are other ways to solve it including setting up something on the server that generates the “correct” JSON to begin with. I wanted to create a drop in solution which is why I went with this approach.

jquery.DateTime.js

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *