Javascript Data Type How to - Format Date to yyyy-mm-dd








Question

We would like to know how to format Date to yyyy-mm-dd.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--  w  w w.  j  a  v a2  s  .c  om-->
function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    return [year, month, day].join('-');
}
document.getElementById('res').innerHTML =  formatDate('Sun May 11,2014') ;
});
</script>
</head>
<body>
  <div id="res">res</div>
</body>
</html>

The code above is rendered as follows: