-1

I tried so many solution on stack overflow itself, but not get the difference in js.

I was using

var days = ('13-10-2018'- '13-09-2018') / (1000 * 60 * 60 * 24)]
Gilad Green
  • 36,708
  • 7
  • 61
  • 95

2 Answers2

1

Well, there are 2 issues here.

First, you need to use your date strings to construct a proper JavaScript Date object, which only supports IETF-compliant RFC 2822 timestamps and also a version of ISO8601, as you can see in MDN. Therefore, you can't use DD-MM-YYYY, but you could use MM-DD-YYYY

Another way to construct a Date object is to use this syntax:

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

So, to calculate the difference between 2 dates in the format DD-MM-YYYY, you first need to parse that and create two Date objects. Then, you call Date.prototype.getTime() in both of them and calculate the absolute difference in milliseconds. Lastly, you convert that to days dividing by 3600000 * 24 and rounding (if you don't want decimal days):

function getDateFromDDMMYYYY(dateString) {
  const [day, month, year] = dateString.split('/');
    
  return new Date(
    parseInt(year),
    parseInt(month) - 1,
    parseInt(day)
  );
}

const diff = Math.abs(getDateFromDDMMYYYY('13/10/2018').getTime() - getDateFromDDMMYYYY('13/09/2018').getTime());
const days = Math.round(diff / (3600000 * 24)); 

console.log(`${ days } ${ days === 1 ? 'day' : 'days' }`);
Danziger
  • 19,628
  • 4
  • 53
  • 83
0

The way you are trying to subtract dates ('13-10-2018'- '13-09-2018') is wrong. This will give an error NaN (Not a number) because '13-10-2018' for instance is a string and can't be automatically converted to a Date object. if you ask '100' - '20' this will give you 80 as javascript automatically parses a string that can be converted to integers or floats when arithmetic operators are applied but in your case, it's '13-10-2018' that can't be parsed either as an integer or float because parsing it won't give any number.

If the date is in string format then you can parse it in following way and then perform some operation, Since your date is in DD-MM-YYYY I suggest you change it either in MM-DD-YYYY or in YYYY-MM-DD, for more info about Date you can look up to the this link.

let timeDifference = Math.abs(new Date('10-13-2018') - new Date('09-13-2018'));
console.log(Math.ceil( timeDifference / (1000 * 60 * 60 * 24)));

new Date('10-13-2018') - new Date('09-13-2018') will give you 2592000000 milliseconds, since time is represented as Unix time. you can check unix time of any date by doing following.

console.log(new Date().getTime('10-13-2018'));

now the calculations behind the scene is 2592000000 / 1000*60*60*24 (that is total milliseconds in one day) = 30 days