Tuesday, 9 April 2013

Convert json date to MM/dd/yyyy

Javascript function to convert a json date into more readable format to user.


// Converts a date received in JSON data from the server in format "\Date(1234567890123)\" to a short
// date string in format MM/dd/yyyy.
function ConvertJsonDateString(jsonDate) {
    var shortDate = null;

    if (jsonDate) {
        var regex = /-?\d+/;
        var matches = regex.exec(jsonDate);
        var dt = new Date(parseInt(matches[0]));
        var month = dt.getMonth() + 1;
        var monthString = month > 9 ? month : '0' + month;
        var day = dt.getDate();
        var dayString = day > 9 ? day : '0' + day;
        var year = dt.getFullYear();
        shortDate = monthString + '/' + dayString + '/' + year;
    }

    return shortDate;
};

10 comments:

  1. Hey buddy,
    thanks a lot,
    its working fine and giving me desire output.

    once again thanks

    ReplyDelete
  2. Great solution! I am required to make a web app work in IE9 and this is the only json to mm/dd/yyyy formatter that works for IE9 as well as the modern browsers.

    ReplyDelete
  3. Great solution, it works perfectly!!!

    ReplyDelete
  4. Thank you so Much..

    ReplyDelete