Javascript Data Type How to - Get Min/Max of dates in an array








Question

We would like to know how to get Min/Max of dates in an array.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--  w  w  w  . j a  v  a  2 s  . co  m-->
function sortDates(a, b)
{
    return a.getTime() - b.getTime();
}
var dates = [];
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/28"))
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/27"))
var sorted = dates.sort(sortDates);
var minDate = sorted[0];
var maxDate = sorted[sorted.length-1];
document.write('minDate = ' + minDate + '<br />maxDate = ' + maxDate);

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

The code above is rendered as follows: