Sunday, June 28, 2009

Best and simple approach to deal with JSON Dates problem

It might be very frustrating for the guys who decided to try for the so called great revolution using jQuery and,WCF and Linq in combination.

Their adventure with the code might come to an end first on the WCF configuration step or secondly handling the JSON serialization over the wire.

Although its really simple to configure the WCF service for your JSON wire transfer requirement but its certainly a little confusing.

Another problem which comes after successful configuration of the WCF services with your application is dealing with “Dates”.

This problem arises due to the fact that there no javascript literal called Date.Everytime we need a date we create a new object of the date such as:-

Date myDate = new Date(“28/04/2008”);


If you write the date like the below given syntax then its not the actual date but its only ordinary string which is of no use as such and does not solve our purpose.

var  myDate = “28/04/2008”;

So the response which you will receive from the server in the JSON format will contain all the dates in a surprising format which can be easily parsed if you are using Micorosft Ajax. But if you are on your own using direct jQuery $ajax() then your life is in trouble.

To workaround this strange Date problem there are few possible ways out of which :-

  1. Parse the response from the server on your own and just use the regex to remove \/ symbol and then evaluating the date string and converting it to Date($1) and returning this date.Although this method is the so called correct one but still its little too complicated and it seems to be the only standard workaround for solving this problem.Given below is some custom implementation for showing how you can parse and evaluate the response received from the server.Always keep in mind that this code would need some change if you are using some other type of replacer symbols in the JSON,this is just a reference example how to parse the response and then evaluating it to get the correct dates.
        type: "POST",
        url: pagePath + "/" + methodName,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "text",
        processData: false,
        success: function(msgg) {
            var msg = JSON.parse(msgg, function(key, value) {
                var a;
                if (value != null) {
                    if (value.toString().indexOf('Date') >= 0) {
                        a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value);
                        if (a) {
                            var dt = new Date(parseInt(a[1], 10));
                            return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
                    return value;
        error: function(xhr, status, error) {
            errorFunction(xhr, status, error);

Here in this example we are getting the actual response in the variable msgg.After invoking the success we are parsing the response and then we are searching for the Date values in the string where ever found we are removing the unnecessary symbols \/ and then parsing the 10 digit date and after this step converting it to actual date and finally returning the value.

Although its a little tricky approach but it works fine,you might have to change the parsing method a little bit as according to your needs to make it work for you.

2.Another simple solution is forget about the Date thing on the client side consider every thing as string on the client and also in your business logic and application layer.Although it doesn’t sounds good and many of us don’t agree on this but its the simplest possible workaround to make things work quickly.

So for achieving this no need to make any changes in your database schema just let the dates be dates only in your schema.

What we will do is we will pass date as string from the UI using BusinessObjects to the Service Layer and DataAccessLayer and after reaching the database we will convert these values back to string and while retrieving those dates from the database they should be converted again back to string so that we are not again running into the same old problem.

Converting date to string while retrieving back the date to be displayed somewhere on the page

CONVERT(CHAR(11),datemodified ,106) AS datemodified,
		CONVERT(CHAR(11),datecreated,106) AS datecreated	

There are various other choices available with changing the last code part to receive date in various other formats.

By using this mechanism you will never run into this date trouble again


Post a Comment