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);

1 comment:

  1. About you: "I read the Bible."

    Therefore you know more about science than all the world's scientists. Therefore the first simple living cells got a foothold on earth thanks to your god fairy's magic wand.

    Also, according to you, anything scientists do is intelligent design. However, unlike your god fairy, scientists don't use magic wands.

    Don't bother polluting my blog again. My blog is not for spreading lies about science. My blog is not for non-scientists who want to show off their love for magic. If you had clicked on my VISITORS link, you would have known you violated several of my rules, including the rule against excessive stupidity. Now my gmail account will automatically vaporize your comments and I will never again have to waste my time reading about your total ignorance of reality.

    ReplyDelete