how many days Between two dates : Date « Development « JavaScript DHTML

how many days Between two dates

     Example File From "JavaScript and DHTML Cookbook"
     Published by O'Reilly & Associates
     Copyright 2003 Danny Goodman

function daysBetween(date1, date2) {
    var DSTAdjust = 0;
    // constants used for our calculations below
    oneMinute = 1000 * 60;
    var oneDay = oneMinute * 60 * 24;
    // equalize times in case date objects have them
    // take care of spans across Daylight Saving Time changes
    if (date2 > date1) {
        DSTAdjust = 
            (date2.getTimezoneOffset() - date1.getTimezoneOffset()) * oneMinute;
    } else {
        DSTAdjust = 
            (date1.getTimezoneOffset() - date2.getTimezoneOffset()) * oneMinute;    
    var diff = Math.abs(date2.getTime() - date1.getTime()) - DSTAdjust;
    return Math.ceil(diff/oneDay);

var projectLength = 0;
// validate form entries with checkDate() function from Recipe 2.12
var startField = document.entryForm.startDate;
var endField = document.entryForm.endDate;
if (checkDate(startField) && checkDate(endField)) {
    var startDate = new Date(startField.value);
    var endDate = new Date(endField.value);
    projectLength = daysBetween(startDate, endDate);
if (projectLength > 0) {
    alert("You\'ve specified " + projectLength + " days for this project.");


Related examples in the same category

1.Demo all methods in Date class
2.Today's Date
3.Display date: day month year in string
4.Date: date, month, and year.
5.Set date: setDate, setHour
6.UTC time: getUTCDate returns the Universal Coordinated Time
7.Display weekday: name of the current day
8.Display full date : complete date with the day name and month name
9.Display time: continues writing time per second.
10.Date: Week of the year
11.Display current date: year, month day in number
12.Extending the Date Object to Include Some New Methods
13.Methods and Properties of the Date Object
14.Using the Date Object
15.Output day
16.A Dynamic Welcome Message
17.How Many Days Until Christmas
18.Summer Games Countdown
19.Simple Date Validation
20.GMT Calculator
21.Days Before Next Christmas Xmas
22.Get how many days before a date