Javascript Data Type How to - Compare two dates to get a difference








Question

We would like to know how to compare two dates to get a difference.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from  ww w.  jav  a 2s .  co  m-->
Date.prototype.addDays = function (days) {
    this.setDate(this.getDate() + days);
    return this;
};
function val_date(input) {
    var inputDate = new Date(input);
    var dateWeek = new Date().addDays(7);
    document.writeln(inputDate, dateWeek);
    document.writeln('<br/>');
    if (inputDate < dateWeek) {
        // The selected time is less than 7 days from now
        return false;
    } else {
        // The selected time is more than 7 days from now
        return true;
    }
}
document.writeln(val_date('11/21/2013'));

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

The code above is rendered as follows: