We would like to know how to count the number of days between two dates.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- w w w. j a v a 2s. c o m-->
Date.prototype.getYMD = function() {
return this.getFullYear() + '-' + (this.getMonth()+1) + '-' + this.getDate();
};
Date.prototype.getDaysDiff = function(d2) {
var d1 = this,
delta = d1 < d2 ? +1 : -1;
var days = 0;
while (d1.getYMD() != d2.getYMD()) {
days++;
d1.setDate(d1.getDate() + delta);
}
return delta * days;
}
d1 = new Date('October 16 2012');
d2 = new Date('November 7 2012');
document.writeln(d1.getDaysDiff(d2));
</script>
</head>
<body>
</body>
</html>
The code above is rendered as follows: