Javascript Data Type How to - Format date as YYYYMMDD '20150707'








Question

We would like to know how to format date as YYYYMMDD '20150707'.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function yyyymmdd(dateIn) {<!--   www.  ja v a  2 s . co  m-->
   var yyyy = dateIn.getFullYear();
   var mm = dateIn.getMonth()+1; // getMonth() is zero-based
   var dd  = dateIn.getDate();
   return String(10000*yyyy + 100*mm + dd); // Leading zeros for mm and dd
}
var today = new Date();
document.writeln(yyyymmdd(today));

</script>
</head>
<body>

</body>
</html>

The code above is rendered as follows: