jQuery: Get formatted Date from returned JSON data

Recently I was working on using client side template to show a tabular data and one of the columns was a date field. The return data was an enumerable type i.e. List of objects containing the System.DateTime (date) field for representing date. When I looked into the date column in my client side grid on browser I was surprised to see the resulted date in form of “/Date(998667000000)/” (the date data might not be exact as I have put how it looks like) which of kind of unexpected and then led to find how to get javascript Date object from the JSON returned date.

So, In the returned data we get JSON serialized date which is in ticks and hence causes problems at the client end as we can’t treat it as javascript date. Eval() fails in coverting it and returns error saying that the format of date is not correct. Now, to resolve this I liked this approach. Use the reviver function which can be used while doing JSON data parsing with JSON.parse function. You can look at http://www.json.org/js.html to know more about reviver funciton.

[from json.ord]
var myObject = JSON.parse(myJSONtext, reviver);

The optional reviver parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects.

[/from json.ord]

So, here is a sample jQuery ajax call implementation which can be used as part of any event in your javascript file and would work for you. The pre-requisite here is to have JSON.js file included so that JSON object is understood by the interpreter and it doesnt break client side code.


//methodName -> The WebMethod name you want to call from ajax
//paramArray  -> Array of parameters which will be converted as JSON params in this function
//successFunction  -> name of successfunction to be called if ajax call succeeds
//errorFunction-> name of error Function to be called if ajax call fails

function ClientProxyDateFormatted(methodName, paramArray, successFunction, errorFunction) {
    var pagePath = window.location.pathname;
    var paramList = '';

    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '"' + ':' + '"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    $.ajax({
        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) {
                        //here we will try to extract the ticks from the Date string in the "value" fields of JSON returned data
                        a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value);
                        if (a) {
                            var dt = new Date(parseInt(a[1], 10));
                            //getMonth return months with index 0 so you need to add 1 to get the correct month value.
                            return dt.getMonth() + 1 + "/" + dt.getDate() + "/" + dt.getFullYear();
                        }
                    }
                    return value;
                }
            });
            successFunction(msg);
        },
        error: function() {
            errorFunction();
        }
    });
    return false;
}

This seemed to me as a good problem and hence I think it would be useful to you in case you are facing similar issue. Let me know if it helps or doesnt help 🙂

bye for now.

-Sushant

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Who am I what am I doing?

Who am I what am I doing?

%d bloggers like this: