-1

I need to find the difference between two dates. If the difference is greater than 6 then display a message in Java Script.

I tried below logic but somehow it is not working.

var sFromDate = new Date(Mon Jun 01 2020 00:00:00 GMT-0400);
var sToDate = new Date(Mon Nov 30 2020 23:59:59 GMT-0500);
var diff = sToDate.getTime() - sFromDate.getTime();
diff = diff / (1000 * 60 * 60 * 24 * 30);
if (diff > 6) {
    alert('Not more than 6 months')
}

In the above example. I am still getting the alert even the range is within 6 months.

Can someone help me in finding the logic the difference between 2 dates should not be more than 6 months.

3 Answers3

0

You can check this answer. In your case the code would be-

function monthDiff(dateFrom, dateTo) {
 return dateTo.getMonth() - dateFrom.getMonth() + 
   (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}

const sFromDate = new Date("Mon Jan 01 2020 00:00:00 GMT-0400");
const sToDate = new Date("Mon Nov 30 2020 23:59:59 GMT-0500");

const diff = monthDiff(sFromDate, sToDate);

if (diff > 6) alert('Not more than 6 months');

console.log('Diff in months: ', diff);
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
0

Take the first date and add 6 months, then check that against the second date:

const date1 = new Date('Mon Jun 01 2020 00:00:00 GMT-0400');
const date2 = new Date('Mon Nov 30 2020 23:59:59 GMT-0500');
const plus6Months = new Date(date1.getYear(), date1.getMonth()+6, date1.getDay());

if (date2.getTime() > plus6Months.getTime())
  console.log('dates are more than 6 months apart');
else if (date2.getTime() < plus6Months.getTime())
  console.log('dates are less than 6 months apart');
else 
  console.log('dates are exactly 6 months apart');
phuzi
  • 12,078
  • 3
  • 26
  • 50
-1
var sFromDate = new Date(Mon Jun 01 2020 00:00:00 GMT-0400);
var sToDate = new Date(Mon Nov 30 2020 23:59:59 GMT-0500);
var months = (sToDate.getFullYear() - sFromDate.getFullYear()) * 12;
months -= sFromDate.getMonth();
months += sToDate.getMonth();
if (months > 6) {
    alert('Not more than 6 months')
}