How can the below code be modified such that the date will appear as: 30/01/2013 as opposed to its current state of: 30/1/2013?
var d = new Date();
var xdate = [d.getDate(), d.getMonth()+1, d.getFullYear()].join('/');
How can the below code be modified such that the date will appear as: 30/01/2013 as opposed to its current state of: 30/1/2013?
var d = new Date();
var xdate = [d.getDate(), d.getMonth()+1, d.getFullYear()].join('/');
Here's a short (left) padding function:
function zeroPad(nr,base,chr){
var len = (String(base||10).length - String(nr).length)+1;
return len > 0? new Array(len).join(chr||'0')+nr : nr;
}
//usage
zeroPad(2); //=> '02'
zeroPad(22); //=> '22'
zeroPad(22,100); //=> '022'
zeroPad(22,100,'x'); //=> 'x22'
I use this general-purpose pad function:
function pad(input,char,width,onleft) {
input = ""+input;
var add = new Array(input.length-width+1).join(char);
if( onleft) return add+input;
else return input+add;
}
Applied to your code, it would be:
var d = new Date();
var xdate = [d.getDate(), pad(d.getMonth()+1,"0",2,true), d.getFullYear()].join("/");
var xdate = [d.getDate(), ('0' + (d.getMonth()+1)).slice(-2), d.getFullYear()].join('/');
Try:
var d = new Date(),
m = d.getMonth()+1,
xdate = [d.getDate(), (m < 10) ? '0' + m : m, d.getFullYear()].join('/');
I'd like to recommend you a mega library moment.js it's easy and fast.
moment().format("YYYY-MM-DD")
result is "2013-01-30"
There are a few ways you could do this by checking if the month is < 10 and then add the 0, I am not a fan of that though, when working with date times in Javascript I find http://blog.stevenlevithan.com/archives/date-time-format this is a great library that handles formatting perfectly