Rishabh Shah
Rishabh Shah

Reputation: 580

Calculate month with days in javascript

I want to calculate month with days in javascript.

I have requirement like My date range will be within 24 months.

I have todate comes from somewhere that is 24 Sep 2012

Now,

if I enter 31 Aug 2010 in from date and 24 Sep 2012 in todate, it shows an error message.

Currently I am doing like that

todate.getMonth() - fromdate.getMonth() + (12 * (todate.getFullYear() - fromdate.getFullYear()))

but, if I enter 23 Sep 2010 in from date and 24 Sep 2012, it should also show error message..

but, its allowing me that date..which is 24 month beyond date..so, how can I calculate month with date which does not allow my above given date.

Thanks

Upvotes: 1

Views: 805

Answers (2)

internals-in
internals-in

Reputation: 5038

Try this to get Days


function finddays(date_from, date_to) 
{return Math.round(Math.abs(new Date(date_from).getTime() - new Date(date_to).getTime())/(1000 * 60 * 60 * 24))}

use:

finddays("23 Sep 2010", "25 Sep 2010");

Update

Not Recommending but works better
Try this to get months (hopes a month of 30 days , Error prone +-3/yr)


 function findMonths(date_from, date_to) 
    {return Math.round((new Date(date_to).getTime()-new Date(date_from).getTime())/(1000 * 60 * 60 * 24*30))}

use:

findMonths("23 Sep 2010", "25 Oct 2010");

Upvotes: 1

Tibos
Tibos

Reputation: 27833

Your problem is that when it's the same month two years apart, you need to also check the day of the month.

function isValidDate (from, to) {
  var months = to.getMonth() - from.getMonth() + 
              (12 * (to.getFullYear() - from.getFullYear()));
  return months < 24 || months === 24 && to.getDate() < from.getDate();
}

Upvotes: 1

Related Questions