Pages

Wednesday, February 12, 2014

Javascript - Work With JSON Datetime

Sometimes when we work with JSON datetimes we get a little stuck, because we want to do all the work client side, using javascript only.

 So, to achieve this, to transform something like this:

"/Date(1392291352347)/"

into this:

"2014-02-13 11:35:52"

we can use a function like this one:

function formatDatetime(jsondate) {

    var match;
    if (jsondate == null || !(match = jsondate.match(/\d+/))) {
        return "";
    }

    var d = new Date();
    d.setTime(match[0] - 0);

    var month = d.getMonth() + 1;
    var day = d.getDate();
    var hour = d.getHours();
    var minute = d.getMinutes();
    var second = d.getSeconds();

    var output = d.getFullYear() + '-' +
    (('' + month).length < 2 ? '0' : '') + month + '-' +
    (('' + day).length < 2 ? '0' : '') + day + ' ' +
    (('' + hour).length < 2 ? '0' : '') + hour + ':' +
    (('' + minute).length < 2 ? '0' : '') + minute + ':' +
    (('' + second).length < 2 ? '0' : '') + second;

    return output;
}

References:
http://stackoverflow.com/questions/9050763/format-date-in-jquery
http://stackoverflow.com/questions/4586424/how-do-i-convert-this-json-datetime