문제

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

도움이 되었습니까?

해결책

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();
}

다른 팁

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");

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top