Javascript Data Type How to - Add 0 in front of every single day or month for single digit








Question

We would like to know how to add 0 in front of every single day or month for single digit.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from   w w  w . ja v a  2s . c  o m-->
    date = "4-1-2013";
    date = date.split('-');
    day = date[0].length == 1 ? "0" + date[0] : date[0];
    month = date[1].length == 1 ? "0" + date[1] : date[1];
    date = "" + day + month + date[2];
    document.writeln(date);
}
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: