Javascript Data Type How to - Add Leading 0 for days and months where applicable








Question

We would like to know how to add Leading 0 for days and months where applicable.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from  ww  w  .  j  av a2  s . c om-->
Date.prototype.ISO8601date = function() {
    function fix2(n) {
        return (n < 10) ? '0' + n : n;
    }
    return this.getFullYear() + '-' + fix2(this.getMonth() + 1) + '-' + fix2(this.getDate());
}
var d = new Date();
var s = d.ISO8601date();
document.writeln(s);

var myDate = new Date();
var m = myDate.getMonth();
var d = myDate.getDate();
m = (m+"").length > 1 ? m : "0"+m;
d = (d+"").length > 1 ? d : "0"+d;
var prettyDate =(myDate.getFullYear() +'-'+ m) +'-'+ d;
document.writeln(prettyDate);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: