Navigation

7/24/2014

Format date with javascript

Looking to format date in standard   mm/dd/yyyy



 
var d = new Date();

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;

See this jsfiddle for a proof: http://jsfiddle.net/nCE9u/3/
You can also enclose it within function (demo is here: http://jsfiddle.net/nCE9u/4/):
 
function getISODateTime(d){
    // padding function
    var s = function(a,b){return(1e15+a+"").slice(-b)};

    // default date parameter
    if (typeof d === 'undefined'){
        d = new Date();
    };

    // return ISO datetime
    return d.getFullYear() + '-' +
        s(d.getMonth()+1,2) + '-' +
        s(d.getDate(),2) + ' ' +
        s(d.getHours(),2) + ':' +
        s(d.getMinutes(),2) + ':' +
        s(d.getSeconds(),2);
}

and use it like that:
 
getISODateTime(new Date());

or:
getISODateTime(some_other_date);

This question is a duplicate (see: How to get current date in jquery?).



http://stackoverflow.com/questions/9050763/format-date-in-jquery

No comments:

Post a Comment