Javascript Data Type How to - Get todays date in this format yyyymmdd








Question

We would like to know how to get todays date in this format yyyymmdd.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--   w  w  w .ja  v  a2  s  . c  o  m-->
Date.prototype.toMyString = function () {
    function padZero(obj) {
          obj = obj + '';
          if (obj.length == 1)
              obj = "0" + obj
          return obj;
    }
    var output = "";
    output += this.getFullYear();
    output += padZero(this.getMonth()+1);
    output += padZero(this.getDate());
    return output; 
}
var d = new Date();
document.writeln(d.toMyString());
var otherDate = new Date(2012,0,1);
document.writeln(otherDate.toMyString());

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

The code above is rendered as follows: