344
  1. I am calculating the number of days between the 'from' and 'to' date. For example, if the from date is 13/04/2010 and the to date is 15/04/2010 the result should be

  2. How do I get the result using JavaScript?

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
udaya
  • 9,598
  • 15
  • 48
  • 67

7 Answers7

691
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);

const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
MaxVT
  • 12,989
  • 6
  • 36
  • 50
  • 84
    Warning: not all days are 24 hours long. If your date range spans a daylight saving change, you'll lose or gain an hour (typically). Use Math.round() on the result (avoid floor or ceil). – Mark Sep 20 '11 at 02:33
  • 12
    In fact i'd preffer Math.ceil here since even if 2.01 days are left saying 3 days left makes more sense that sayin 2 days left. – 5hahiL Nov 17 '12 at 10:20
  • 20
    @Mark 's comment about using Math.round was added to code of the answer. Don't round the result again, like someone I know... (ok it was me) – Aardvark May 14 '14 at 20:38
  • Why doesn't it count it as 5 days when it's between June 1st to June 5th? – adamj Jun 09 '14 at 09:42
  • What about leap years? – Kumait Jul 10 '15 at 09:09
  • @Kumait What about them? – MaxVT Jul 10 '15 at 13:28
  • My fault, this must be handled internally in the Date object – Kumait Jul 13 '15 at 02:13
  • 7
    I tested this with 2015-02-1 to 2015-03-01 and got 31 days. There's something wrong here... EDIT: Okay yeah.. javascript months are from 0-12 so if you're getting the input from a jquery datepicker or a regular normal date, subtract 1 form the month – Robert Mennell Oct 13 '15 at 23:07
  • 19
    Note that this code still takes into account the TIME of the given dates when counting. i.e. checking the number of days between 3PM on the 1st and 00:00:00 on the 2nd will yield zero days. To fix this, set both dates to midnight before comparison, i.e. add: firstDate.setHours(0, 0, 0); secondDate.setHours(0, 0, 0); This way you can say daysBetween(new Date(2016,1,10,15), new Date(2016,1,11))); and still come up with 1 day difference. – Howard Feb 10 '16 at 13:37
  • 2
    Nice, it threw me for a moment that JavaScript has January as 0, so I had put a 1 thinking that was January, but it was actually February, throwing off my calculation. Thanks for this result. – Chris Hawkes Mar 28 '16 at 00:28
  • When I copied this code to my console and after hitting return, I get undefined in my console. Any reason? – Ilyas karim Oct 05 '17 at 15:45
  • @Ilyaskarim if you're using a console, you probably want to see the resulting difference. typing `diffDays` produces the expected result. – MaxVT Oct 19 '17 at 20:55
  • I was having an off by one error depending on the time of day, @Howard 's suggestion fixed my problem! – reggaeguitar Feb 16 '18 at 17:03
  • To prevent red squiggly lines on the last line of the above code, replace the last line with the following code: `const diffDays = Math.round(Math.abs((firstDate.valueOf() - secondDate.valueOf()) / oneDay));` – Devner Jan 16 '22 at 21:27
68

Here is a function that does this:

function days_between(date1, date2) {

    // The number of milliseconds in one day
    const ONE_DAY = 1000 * 60 * 60 * 24;

    // Calculate the difference in milliseconds
    const differenceMs = Math.abs(date1 - date2);

    // Convert back to days and return
    return Math.round(differenceMs / ONE_DAY);

}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
31

Here's what I use. If you just subtract the dates, it won't work across the Daylight Savings Time Boundary (eg April 1 to April 30 or Oct 1 to Oct 31). This drops all the hours to make sure you get a day and eliminates any DST problem by using UTC.

var nDays = (    Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) -
                 Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;

as a function:

function DaysBetween(StartDate, EndDate) {
  // The number of milliseconds in all UTC days (no DST)
  const oneDay = 1000 * 60 * 60 * 24;

  // A day in UTC always lasts 24 hours (unlike in other time formats)
  const start = Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate());
  const end = Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate());

  // so it's safe to divide by 24 hours
  return (start - end) / oneDay;
}
Xeoncross
  • 55,620
  • 80
  • 262
  • 364
rmcmullan
  • 419
  • 4
  • 3
  • 2
    But if you drop the hours etc., why would you still use UTC? – Rudey Oct 30 '14 at 08:56
  • 2
    @RuudLenders because day in UTC always lasts 24 hours, unlike in other time formats, so it's safe do divide by 24 hours – Dan Apr 26 '17 at 18:56
18

Here is my implementation:

function daysBetween(one, another) {
  return Math.round(Math.abs((+one) - (+another))/8.64e7);
}

+<date> does the type coercion to the integer representation and has the same effect as <date>.getTime() and 8.64e7 is the number of milliseconds in a day.

  • 5
    The type coercion is redundant here because you already use a arithmetic operator to substract the dates (which also results in a type coercion). So you can write it like this: `Math.round(Math.abs(one - another) / 8.64e7);` – A1rPun Aug 25 '15 at 14:23
  • 4
    2019 readers: if you are using typescript, the `+` is required. – Woohoojin Nov 05 '19 at 18:29
11

Adjusted to allow for daylight saving differences. try this:

  function daysBetween(date1, date2) {

 // adjust diff for for daylight savings
 var hoursToAdjust = Math.abs(date1.getTimezoneOffset() /60) - Math.abs(date2.getTimezoneOffset() /60);
 // apply the tz offset
 date2.addHours(hoursToAdjust); 

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}

// you'll want this addHours function too 

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}
Damen TheSifter
  • 901
  • 1
  • 6
  • 17
  • 2
    There is no need to adjust for the timezone offset, the time value is in UTC. If there is a need for timezone adjustment, it can be applied directly to the minutes using `setMinutes()` rather than converting to hours and using `setHours()`. The arguments to the `set` methods should be integers. If using `setHours` and the offset is not an even multiple of hours, the value will be truncated. – RobG Nov 23 '12 at 22:27
9

I have written this solution for another post who asked, how to calculate the difference between two dates, so I share what I have prepared:

// Here are the two dates to compare
var date1 = '2011-12-24';
var date2 = '2012-01-01';

// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');

// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);

// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);

// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;

// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;

// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours  / 24;

alert(timeDifferenceInDays);

You can skip some steps in the code, I have written it so to make it easy to understand.

You'll find a running example here: http://jsfiddle.net/matKX/

Armin
  • 15,582
  • 10
  • 47
  • 64
  • 3
    Note that months are zero indexed, so you should have `new Date(date1[0], --date1[1], date1[2]);`. Also, using `parseInt` will truncate the milliseconds. Simpler to just subtract the date objects and convert the difference to days: `Math.round((date1 - date2) / 8.64e7)` or if whole days are required with no rounding, just truncate the decimal part: `(date1 - date2) / 8.64e7 | 0`. – RobG Nov 23 '12 at 22:20
1

From my little date difference calculator:

var startDate = new Date(2000, 1-1, 1);  // 2000-01-01
var endDate =   new Date();              // Today

// Calculate the difference of two dates in total days
function diffDays(d1, d2)
{
  var ndays;
  var tv1 = d1.valueOf();  // msec since 1970
  var tv2 = d2.valueOf();

  ndays = (tv2 - tv1) / 1000 / 86400;
  ndays = Math.round(ndays - 0.5);
  return ndays;
}

So you would call:

var nDays = diffDays(startDate, endDate);

(Full source at http://david.tribble.com/src/javascript/jstimespan.html.)

Addendum

The code can be improved by changing these lines:

  var tv1 = d1.getTime();  // msec since 1970
  var tv2 = d2.getTime();
David R Tribble
  • 11,918
  • 5
  • 42
  • 52
  • I had to take out the - 0.5 from the round function for it to work properly for some reason, I'm thinking it was because of the minus 1 for the month since its 0 indexed – Yohn May 19 '15 at 15:35