856

How do I get the difference between 2 dates in full days (I don't want any fractions of a day)

var date1 = new Date('7/11/2010');
var date2 = new Date('12/12/2010');
var diffDays = date2.getDate() - date1.getDate(); 
alert(diffDays)

I tried the above but this did not work.

5
  • 47
    Just a side note: do not create Date objects with these kind of strings as input; it's non-standard and up to the browser how those are parsed. Use strings that can be parsed by Date.parse or, rather, use three numeric values as the arguments to new Date, e.g. new Date(2010, 11, 7);. Jul 11, 2010 at 22:53
  • 4
    Side-note: Never trust the system time on client-side! It's wrong quite often, you might break your application.
    – Sliq
    Mar 15, 2015 at 13:06
  • Also, try a small function at stackoverflow.com/a/53092438/3787376.
    – Edward
    Nov 3, 2018 at 21:57
  • 6
    @Edward, you really call that a SMALL function? :)
    – Ihor
    Dec 19, 2019 at 8:58
  • 1
    This is unsolvable. 1) 7/11/2010 could be July 11th, or November 7th. 2) What timezone? This could span the dateline. 3) with no time, the accuracy is +/- 1 day. 4) the result could be - when really it is positive (or vise versa) since there is no time/timezone
    – Andrew
    Sep 8, 2021 at 15:44

5 Answers 5

1284

Here is one way:

const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");

Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.

25
  • 13
    As volkan answered below, the 1000 * 3600 * 24 is the number of milliseconds per day. As for always returning a positive number, that was a feature :) Typically when one talks about the number of days between two dates, that number is positive. If direction matters, just remove the Math.abs().
    – TNi
    Jul 11, 2010 at 22:38
  • 2
    Likewise, you get 1 day with your method, because getDate() returns the day without regards to the month. Thus, you would get 12 - 11 = 1.
    – TNi
    Jul 11, 2010 at 22:40
  • 5
    date already returned time do not need to call .getTime()
    – volkan er
    Jul 11, 2010 at 22:56
  • 13
    For this to work correctly with daylight saving, Math.round should replace Math.ceil. But I think Shyam's answer is the way to go. Jun 24, 2013 at 10:31
  • 10
    Won't work with a 23 hour 25 hour day in the calculated span. It would be helpful to consult a detailed treatment of UTC (Universal Coordinated Time) and "civil" time standards before devising a calculation such as this. A day is not a always 86,400 seconds, not even in UTC. However, ECMA standards state that it will not have the 58, 59, 61, or 62 second minutes that occur up to twice a year in UTC. You must not assume that offsets from epoch (00:00:00 hours 1 January 1970) in other languages and operating systems will be the same since some of them have 58, 59, 61, and 62 second minutes.
    – Jim
    Mar 8, 2015 at 3:13
1015

A more correct solution

... since dates naturally have time-zone information, which can span regions with different day light savings adjustments

Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24, so the typical calculation will fail.

You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.

Now, the solution can be written as,

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  const _MS_PER_DAY = 1000 * 60 * 60 * 24;
  // Discard the time and time-zone information.
  const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// test it
const a = new Date("2017-01-01"),
    b = new Date("2017-07-25"),
    difference = dateDiffInDays(a, b);
    
console.log(difference + ' days')

This works because UTC time never observes DST. See Does UTC observe daylight saving time?

p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.

39
  • 68
    this is the ONLY correct answer, i don't understand why other answer if accepted
    – obenjiro
    Apr 5, 2013 at 8:26
  • 29
    probably because @chobo2 has not come back and looked at this question Apr 6, 2013 at 20:47
  • 6
    @Ai_boy: While this is the most logically correct answer, there are no values for which it will fail to match the simpler Math.round((b - a)/ _MS_PER_DAY, 0), so it's difficult to support "the ONLY correct answer". Aug 21, 2013 at 0:56
  • 1
    @ShyamHabarakada: That's a problem with a Math.ceil or Math.floor technique, but since daylight savings only adjusts by one hour from a 24-hour day, it will be swallowed up by Math.round. I haven't tested exhaustively, but I can see no case where the two would disagree. Can you? We're actually discussing this in 18347050, which is how I ran across this old thread, and I brought up Daylight Savings there. Aug 21, 2013 at 1:30
  • 14
    Using UTC instead of a local time zone will correct the problems caused by 23 hour and 25 hour days in civil time systems. UTC also has 58, 59, 61, and 62 second minutes up to twice a year, so a day in UTC will not always have 86,400 seconds. However, ECMA standards state that JavaScript does not incorporate these adjustments so ignoring them when working purely in JavaScript works. However, other system do not ignore them and you must not assume offsets from the epoch moment (00:00:00 January 1, 1970) will always be the same between programming languages and operating systems.
    – Jim
    Mar 8, 2015 at 3:03
58
var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 

alert(diffDays )
9
  • 1
    date2 - date1 => milliseconds output (1000 * 60 * 60 * 24) => milisecond to day
    – volkan er
    Jul 11, 2010 at 22:36
  • 11
    Isn't parseInt completely unnecessary?
    – Christian
    Jul 11, 2010 at 23:02
  • 3
    Christian: he wanted an integral number. parseInt is probably the worst way to do it. Math.round is the 'normal' way; it rounds instead of truncating. If truncating was desired, 'or'ing the expression with 0 would suffice: (date2 - date1) / (1000 * 60 * 60 * 24) | 0 Jul 12, 2010 at 0:05
  • 10
    Note that this solution isnt completely accurate as, in some cases i.e. 2015-04-06 minus 2015-04-04 gives an erroneous 1 day, all about parseInt() aproach.
    – ontananza
    Mar 24, 2015 at 22:54
  • 1
    @ontananza var date1 = new Date("2015-04-04"); var date2 = new Date("2015-04-06"); parseInt((date2 - date1) / (1000 * 60 * 60 * 24)); yields 2 for me
    – sdfsdf
    Jan 18, 2019 at 20:18
13

I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....

So here's my answer and can be run out of the box.

<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">

<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>

a Fiddle can be seen here DEMO

1
  • This is a similar problem to what I have the problem with this solution is that if the user clicks on the date2 datepicker first, then it fails.
    – user6743474
    May 12, 2018 at 6:30
7

This is the code to subtract one date from another. This example converts the dates to objects as the getTime() function won't work unless it's an Date object.

    var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);

                var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                var diffDays = Math.abs((date1.getTime() - date2.getTime()) / (oneDay));
                alert(diffDays);

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