413

I have two input dates taking from Date Picker control. I have selected start date 2/2/2012 and end date 2/7/2012. I have written following code for that.

I should get result as 6 but I am getting 5.

function SetDays(invoker) {   
    var start = $find('<%=StartWebDatePicker.ClientID%>').get_value();
    var end = $find('<%=EndWebDatePicker.ClientID%>').get_value();

    var oneDay=1000 * 60 * 60 * 24;
    var difference_ms = Math.abs(end.getTime() - start.getTime())
    var diffValue = Math.round(difference_ms / oneDay);
}

Can anyone tell me how I can get exact difference?

5
  • why should you get result = 6??? 07 - 02 = 05 days.... Commented Feb 3, 2012 at 14:13
  • 1
    But the range of days from 2 to 7 is 2,3,4,5,6,7 = 6 days.
    – Supr
    Commented Feb 3, 2012 at 14:16
  • While taking difference I want to consider Start date also.... Commented Feb 3, 2012 at 14:17
  • 20
    Well ... why not just add 1 to the answer?
    – Pointy
    Commented Feb 3, 2012 at 14:33
  • The issue (if there is a issue at all) is functional, not technical. @Pointy comment is the answer. That's why some people ask why we are in XXI century. Commented Mar 6, 2018 at 1:41

8 Answers 8

912

http://momentjs.com/ or https://date-fns.org/

From Moment docs:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days')   // =1

or to include the start:

a.diff(b, 'days')+1   // =2

Beats messing with timestamps and time zones manually.

Depending on your specific use case, you can either

  1. Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by @kotpal in the comments).
  2. Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
  3. Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.
8
  • 47
    moment.js will give negative value if a < b. So, more robust calculation would be: Math.abs(a.diff(b, 'days'))+1 Commented Apr 15, 2016 at 15:16
  • 33
    Be aware to ignore the time-part - or else you would get different results for the same date but with different times (like from a date picker control). use moment(someDate).startOf('day') to explicitly set the time part to 00:00:00 before performing a diff (or any other operations that are sensitive to the time-part of the Date/moment object)
    – kotpal
    Commented Aug 2, 2017 at 5:07
  • This works but it does not take the time component into account. Trying to diff between the following two pairs: (a="2017-12-24T00:00:00Z" and "b=2017-12-31T23:59:59Z") and (a="2017-12-24T23:00:00Z" and b="2017-12-31T23:59:59Z"). return b.diff(a, 'days') <= 7; both return true. Is there a way to include the time component in the diff?
    – Roobie
    Commented Oct 9, 2017 at 3:36
  • 1
    +1 for startOf() and endOf(). I've used this library for a few years and never noticed them before. I always did +1. Commented Jan 25, 2018 at 16:53
  • 5
    Be aware that startOf mutates the moment. If you don't want that, then do a.clone().startOf('day').diff(b.clone().startOf('day')).
    – HRJ
    Commented Jan 1, 2019 at 13:45
91

If you are using moment.js you can do it easily.

var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");

//Difference in number of days
moment.duration(start.diff(end)).asDays();

//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();

If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below

moment().startOf('day')

To find difference between a given date and current date in number of days

var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');

//Difference in number of days
moment.duration(given.diff(current)).asDays();
2
  • 7
    asDays() returned me some values with decimals. I use current.diff(given, 'days') so it rounds up.
    – Vincent
    Commented Mar 22, 2019 at 13:37
  • @Vincent it seems that your are using this the wrong way. this is definitively the more clean solution the result is right compared to the answer of @Supr in which a 1 is lost Commented Nov 20, 2019 at 22:55
23

Try this Using moment.js (Its quite easy to compute date operations in javascript)

firstDate.diff(secondDate, 'days', false);// true|false for fraction value

Result will give you number of days in integer.

1
  • 2
    here is the signature : moment().diff(Moment|String|Number|Date|Array, String, Boolean);
    – Sumit
    Commented May 17, 2018 at 11:43
20

Try:

//Difference in days

var diff =  Math.floor(( start - end ) / 86400000);
alert(diff);
4
  • I think that's basically right but isn't it essentially the same as what's in the OP?
    – Pointy
    Commented Feb 3, 2012 at 14:15
  • Because of the way he wrote it I didn't notice, but yeah, pretty much! :P
    – Richard
    Commented Feb 3, 2012 at 14:22
  • 11
    I don't like magic numbers.. it would be better if that number was broken down to a self-explanatory equation
    – vsync
    Commented Sep 28, 2018 at 15:11
  • This calculation is wrong when crossing boundaries of daylight savings time, because those days have either 23 hours or 25 hours in them.
    – hlynbech
    Commented Mar 26, 2021 at 14:39
19

This works for me:

const from = '2019-01-01';
const to   = '2019-01-08';

Math.abs(
    moment(from, 'YYYY-MM-DD')
      .startOf('day')
      .diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')
  ) + 1
);

5

Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.

5

I made a quick re-usable function in ES6 using Moment.js.

const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {
  const getDateAsArray = (date) => {
    return moment(date.split(/\D+/), date_format);
  }
  return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;
}

console.log(getDaysDiff('2019-10-01', '2019-10-30'));
console.log(getDaysDiff('2019/10/01', '2019/10/30'));
console.log(getDaysDiff('2019.10-01', '2019.10 30'));
console.log(getDaysDiff('2019 10 01', '2019 10 30'));
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));

console.log(getDaysDiff('10-01-2019', '10-30-2019'));
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

0
// today
const date = new Date();

// tomorrow
const nextDay = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);

// Difference in time
const Difference_In_Time = nextDay.getTime() - date.getTime();

// Difference in Days 
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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