572

For example, given two dates in input boxes:

<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>

<script>
  alert(datediff("day", first, second)); // what goes here?
</script>

How do I get the number of days between two dates in JavaScript?

8
  • 20
    99% of the cases where the user asks for "number of days between two dates" what she doesn't understand is that she is trying to compare apples with pears. The problem becomes so simple if asked "How many DATES are there in a DATE RANGE?", Or how many squares I have to cross on the calendar. This leaves off time and daylight saving issues etc etc.The confusion is implied on us because of the datetime data structure which is pure nonsense. There is no such thing as datetime there is date and there is time, two very distinct objects in both nature and behavior May 24, 2017 at 17:07
  • For a function that splits the difference into (whole) units of time, use the answer at stackoverflow.com/a/53092438/3787376.
    – Edward
    Oct 31, 2018 at 21:58
  • 1
    I feel this question should be deleted or at least marked "avoid" as most of the answers are either incorrect or dependent on various libraries.
    – RobG
    Mar 16, 2019 at 22:09
  • @RobG libraries are the only option if JavaScript does not provide a built-in way to do it right.
    – MC Emperor
    Dec 12, 2020 at 14:18
  • 3
    @MCEmperor—hardly, the top voted answer is just 3 lines of code, and two of those are for parsing.
    – RobG
    Dec 12, 2020 at 14:35

43 Answers 43

1
2
2
 // JavaScript / NodeJs answer  
   let startDate = new Date("2022-09-19");
   let endDate = new Date("2022-09-26");

   let difference = startDate.getTime() - endDate.getTime();
   
    console.log(difference);

   let TotalDiffDays = Math.ceil(difference / (1000 * 3600 * 24));
   console.log(TotalDiffDays + " days :) ");
1

The daylight saving issue is invalidating quite a few answers here. I would use a helper function to get a unique day number for a given date -- by using the UTC method:

const dayNumber = a => Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()) / (24*60*60*1000);
const daysBetween = (a, b) => dayNumber(b) - dayNumber(a);

// Testing it
const start = new Date(1000, 0, 1); // 1 January 1000
const end   = new Date(3000, 0, 1); // 1 January 3000
let current = new Date(start);
for (let days = 0; current < end; days++) {
    const diff = daysBetween(start, current);
    if (diff !== days) throw "test failed";
    current.setDate(current.getDate() + 1); // move current date one day forward
}
console.log("tests succeeded");

1

I took some inspiration from other answers and made the inputs have automatic sanitation. I hope this works well as an improvement over other answers.

I also recommend the use of <input type="date"> fields which would help validate user inputs.

//use best practices by labeling your constants.
let MS_PER_SEC = 1000
  , SEC_PER_HR = 60 * 60
  , HR_PER_DAY = 24
  , MS_PER_DAY = MS_PER_SEC * SEC_PER_HR * HR_PER_DAY
;

//let's assume we get Date objects as arguments, otherwise return 0.
function dateDiffInDays(date1Time, date2Time) {
    if (!date1Time || !date2Time) return 0;
    return Math.round((date2Time - date1Time) / MS_PER_DAY);
}

function getUTCTime(dateStr) {
  const date = new Date(dateStr);
  // If use 'Date.getTime()' it doesn't compute the right amount of days
  // if there is a 'day saving time' change between dates
  return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());
}


function calcInputs() {
  let date1 = document.getElementById("date1")
    , date2 = document.getElementById("date2")
    , resultSpan = document.getElementById("result")
  ;
  if (date1.value && date2.value && resultSpan) {
    //remove non-date characters
    console.log(getUTCTime(date1.value));
    let date1Time = getUTCTime(date1.value)
      , date2Time = getUTCTime(date2.value)
      , result = dateDiffInDays(date1Time, date2Time)
    ;
    resultSpan.innerHTML = result + " days";
  }
}
window.onload = function() { calcInputs(); };

//some code examples
console.log(dateDiffInDays(new Date("1/15/2019"), new Date("1/30/2019")));
console.log(dateDiffInDays(new Date("1/15/2019"), new Date("2/30/2019")));
console.log(dateDiffInDays(new Date("1/15/2000"), new Date("1/15/2019")));
<input type="date" id="date1" value="2000-01-01" onchange="calcInputs();" />
<input type="date" id="date2" value="2022-01-01" onchange="calcInputs();"/>
Result: <span id="result"></span>

1
  • 2
    Instead of using 'date1.getTime()' and 'date2.getTime()' I use 'Date.UTC' to prevent difference between dates that does not belong to the same day saving time (i.e. March 10, 2021 and March 16, 2021) the following function may help: function getUTCTime(date) { // If use 'Date.getTime()' it doesn't compute the right amount of days // if there is a 'day saving time' change between dates return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()); }
    – Chesare
    Mar 16, 2021 at 20:52
1

The easiest answer, accounting for time of day and leap years, boils down to five lines of code. You only need three lines of code if know that your entries will never have a time component.

  date1 = new Date("1/1/2000");
  date2 = new Date("1/1/2001");
  date1.setHours(0, 0, 0, 0); // this line accounts for date strings that have time components
  date2.setHours(0, 0, 0, 0); // this too
  daysBetween = Math.round((date2 - date1) / (24 * 60 * 60 * 1000));

I've included a fully documented function called daysDiff that accepts JavaScript date objects and throws errors if the parameters are malformed.

/**
 * Calculate the number of days between two dates, taking into account possible leap years.
 * Returns a positive or negative integer.
 *
 * @param {Date} date1 - The earlier of the two dates.
 * @param {Date} date2 - The later of the two dates.
 * @throws {TypeError} - If either dateOne or dateTwo is not a valid Date object.
 * @returns {number}   - Integer number of days between date1 and date2.
*/
function daysDiff(date1, date2) {
  // Ensure date1 and date2 are valid Date objects
  if (!(date1 instanceof Date) || !(date2 instanceof Date)) {
      throw new TypeError('Both date1 and date2 must be valid Date objects.');
  }

  const millisecondsPerDay = 24 * 60 * 60 * 1000;
  
  // Reset time components to midnight to consistent days between without worrying about times.
  date1.setHours(0, 0, 0, 0);
  date2.setHours(0, 0, 0, 0);
  
  // Calculate the difference in milliseconds and convert to days
  return Math.round((date2 - date1) / millisecondsPerDay);
}

// accounts for leap year
console.log(daysDiff(new Date("1/1/2024"), new Date("4/30/2024")));

// returns the number of days between today and Jan 1, 2023
console.log(daysDiff(new Date("1/1/2023"), new Date()));

// returns a negative number as date1 is bigger than date2
console.log(daysDiff(new Date("1/30/2024"), new Date("1/1/2024")));

// ignores the time component so will return same result any time of day
console.log(daysDiff(new Date("1/30/2024 13:40:00", new Date())));

// throws an error because date1, while true, isn't a date.`
console.log(daysDiff("frogs are great", new Date()));
2
  • How is "subtract one date from another" any different than the other 2 pages of answers here, including the almost 15 year old accepted answer?
    – miken32
    Aug 23, 2023 at 17:14
  • @miken32 My answer is more generic. The accepted answer provides no easy way to accommodate something as simple as today's date Date(). The time component will lead to inconsistent results. The closest answer to mine is from Sumit Joshi, with two upvotes which I missed the first time going through this. The only difference between his and mine is that mine is better documented. I'll pull mine if it's too redundant.
    – bookworm
    Aug 23, 2023 at 18:35
0

You can use UnderscoreJS for formatting and calculating difference.

Demo https://jsfiddle.net/sumitridhal/8sv94msp/

 var startDate = moment("2016-08-29T23:35:01");
var endDate = moment("2016-08-30T23:35:01");  
  

console.log(startDate);
console.log(endDate);

var resultHours = endDate.diff(startDate, 'hours', true);

document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(resultHours));
body { white-space: pre; font-family: monospace; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>

0

Using moment will be much easier in this case, You could try this:

    let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days');

It will give you integer value like 1,2,5,0etc so you can easily use condition check like:

if(days < 1) {

Also, one more thing is you can get more accurate result of the time difference (in decimals like 1.2,1.5,0.7etc) to get this kind of result use this syntax:

let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days', true);

Let me know if you have any further query

0

The elephant in the room is that there's no single right answer!

If you just want the number of 24 hour periods between 2 dates then just subtract them, divide by 86400000, round up or down depending on your personal requirement and you're done.

If you want the number of calendar days it depends what time zone you're in: Say it's 11pm and you're in Bangkok, in 2 hours time it will be a different day for you, but for someone in LA it will be the same day.

Only if you're sure that (a) both the dates you're comparing (b) the timezone of your JavaScript instance (c) the person who wants to know the answer, are all in the same time zone, then you can do the calculation using local times.

In all other cases you need to think more carefully about what you're trying to achieve. For instance if one of the input dates is in Bangkok and the other is in LA then the number of days difference could still be 1 even if the two input values are identical.

In my case I don't know the time zone of either or the input dates or the person who's reading the output, so I decided to calculate what the number of calendar days would be in UTC like this:

(
    Date.UTC(d1.getUTCFullYear(), d1.getUTCMonth(), d1.getUTCDate()) 
    -
    Date.UTC(d2.getUTCFullYear(), d2.getUTCMonth(), d2.getUTCDate())
) / 86400000
-1
   function validateDate() {
        // get dates from input fields
        var startDate = $("#startDate").val();
        var endDate = $("#endDate").val();
        var sdate = startDate.split("-");
        var edate = endDate.split("-");
        var diffd = (edate[2] - sdate[2]) + 1;
        var leap = [ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
        var nonleap = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
        if (sdate[0] > edate[0]) {
            alert("Please enter End Date Year greater than Start Date Year");
            document.getElementById("endDate").value = "";
            diffd = "";
        } else if (sdate[1] > edate[1]) {
            alert("Please enter End Date month greater than Start Date month");
            document.getElementById("endDate").value = "";
            diffd = "";
        } else if (sdate[2] > edate[2]) {
            alert("Please enter End Date greater than Start Date");
            document.getElementById("endDate").value = "";
            diffd = "";
        } else {
            if (sdate[0] / 4 == 0) {
                while (sdate[1] < edate[1]) {
                    diffd = diffd + leap[sdate[1]++];
                }
            } else {
                while (sdate[1] < edate[1]) {
                    diffd = diffd + nonleap[sdate[1]++];
                }
            }
            document.getElementById("numberOfDays").value = diffd;
        }
    }
0
-1

Bookmarklet version of other answers, prompting you for both dates:

javascript:(function() {
    var d = new Date(prompt("First Date or leave blank for today?") || Date.now());
    prompt("Days Between", Math.round(
        Math.abs(
            (d.getTime() - new Date(prompt("Date 2")).getTime())
                /(24*60*60*1000)
             )
        ));
})();
-1

I only got two timestamps in millisecond, so I have to do some extra steps with moment.js to get the days between.

const getDaysDiff = (fromTimestamp, toTimestamp) => {
    // set timezone offset with utcOffset if needed
    let fromDate = moment(fromTimestamp).utcOffset(8);
    let toDate = moment(toTimestamp).utcOffset(8);
    // get the start moment of the day
    fromDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
    toDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
    let diffDays = toDate.diff(fromDate, 'days');

    return diffDays;
}

getDaysDiff(1528889400000, 1528944180000)// 1 
-1

A contribution, for date before 1970-01-01 and after 2038-01-19

function DateDiff(aDate1, aDate2) {
  let dDay = 0;
  this.isBissexto = (aYear) => {
    return (aYear % 4 == 0 && aYear % 100 != 0) || (aYear % 400 == 0);
  };
  this.getDayOfYear = (aDate) => {
    let count = 0;
    for (let m = 0; m < aDate.getUTCMonth(); m++) {
      count += m == 1 ? this.isBissexto(aDate.getUTCFullYear()) ? 29 : 28 : /(3|5|8|10)/.test(m) ? 30 : 31;
    }
    count += aDate.getUTCDate();
    return count;
  };
  this.toDays = () => {
    return dDay;
  };
  (() => {
    let startDate = aDate1.getTime() <= aDate2.getTime() ? new Date(aDate1.toISOString()) : new Date(aDate2.toISOString());
    let endDate = aDate1.getTime() <= aDate2.getTime() ? new Date(aDate2.toISOString()) : new Date(aDate1.toISOString());
    while (startDate.getUTCFullYear() != endDate.getUTCFullYear()) {
      dDay += (this.isBissexto(startDate.getFullYear())? 366 : 365) - this.getDayOfYear(startDate) + 1;
      startDate = new Date(startDate.getUTCFullYear()+1, 0, 1);
    }
    dDay += this.getDayOfYear(endDate) - this.getDayOfYear(startDate);
  })();
}
-1

This answer, based on another one (link at end), is about the difference between two dates.
You can see how it works because it's simple, also it includes splitting the difference into
units of time (a function that I made) and converting to UTC to stop time zone problems.

function date_units_diff(a, b, unit_amounts) {
    var split_to_whole_units = function (milliseconds, unit_amounts) {
        // unit_amounts = list/array of amounts of milliseconds in a
        // second, seconds in a minute, etc., for example "[1000, 60]".
        time_data = [milliseconds];
        for (i = 0; i < unit_amounts.length; i++) {
            time_data.push(parseInt(time_data[i] / unit_amounts[i]));
            time_data[i] = time_data[i] % unit_amounts[i];
        }; return time_data.reverse();
    }; if (unit_amounts == undefined) {
        unit_amounts = [1000, 60, 60, 24];
    };
    var utc_a = new Date(a.toUTCString());
    var utc_b = new Date(b.toUTCString());
    var diff = (utc_b - utc_a);
    return split_to_whole_units(diff, unit_amounts);
}

// Example of use:
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(
   /0|1|2/g, function (x) {return String( d[Number(x)] );} ));

How my code above works

A date/time difference, as milliseconds, can be calculated using the Date object:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

Then to work out the number of seconds in that difference, divide it by 1000 to convert
milliseconds to seconds, then change the result to an integer (whole number) to remove
the milliseconds (fraction part of that decimal): var seconds = parseInt(diff/1000).
Also, I could get longer units of time using the same process, for example:
- (whole) minutes, dividing seconds by 60 and changing the result to an integer,
- hours, dividing minutes by 60 and changing the result to an integer.

I created a function for doing that process of splitting the difference into
whole units of time, named split_to_whole_units, with this demo:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

This answer is based on this other one.

0
-2

This is bit different answer if we want to calculate our age

    {
      birthday: 'April 22, 1993',
      names: {
        first: 'Keith',
        last: 'Buckley'
      }
    },
    {
      birthday: 'January 3, 1975',
      names: {
        first: 'Larry',
        last: 'Heep'
      }
    },
    {
      birthday: 'February 12, 1944',
      names: {
        first: 'Linda',
        last: 'Bermeer'
      }
    }
  ];
const cleanPeople = people.map(function ({birthday, names:{first, last}}) {
      // birthday, age, fullName;
      const now = new Date();
      var age =  Math.floor(( Date.parse(now) - Date.parse(birthday)) / 31536000000);
      return {
        age,
        fullName:`${first} ${last}`
      }
    });
    console.log(cleanPeople);
    console.table(cleanPeople);
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.