Tuesday, June 8, 2010

Javascript date as two digits

Javascript lacks some string manipulation functions that might be handy when trying to output a date as two digits.

I was trying to format a date as "YYYY-MM-DD" and discovered that there is no equivalent of right$ in Javascript. So I did it this way:

var day=new Date();
day>9 ? day.toString() : "0"+day;


If it matters, here is the code to render the date, making sure that days before the 10th and months before October include the leading zero character:

var now = new Date();
var month = now.getMonth()+1;
var day = now.getDate();
document.getElementById('date').value=now.getFullYear()+"-"+
(month > 9 ? month : "0" + month) + "-" +
(day > 9 ? day : "0" + day);