开发者

Validating the last date of a month

I have two functions that calculate the last date of a month entered by a user

var effectiveAsOfDateYear = document.forms[0].effectiveAsOfDateYear.value;   
var effectiveAsOfDateMonth = document.forms[0].effectiveAsOfDateMonth.value;          
var effectiveAsOfDateDay = document.forms[0].effectiveAsOfDateDay.value;                

userEnteredDate = effectiveAsOfDateDay; 

userEnteredMonth = effectiveAsOfDateMonth;

// **Then using if condition** 
if (!isLastDayOfMonth(userEnteredDate, userEnteredMonth))   {
alert("Inside isLastDayOfMonth of continueUploadReportAction ");
// Do something         
}
------------------------------------------------------------------
// The function is defined as below **strong text**          
function isLastDayOfMonth( date, month ) {
alert("Inside isLastDayOfMonth, the date is " + date );
alert("Inside isLastDayOfMonth, the month is " + month );
return ( date.toString() == new Date( date.getFullYear(), month, 0, 0, 0, 0, 0 ).toString() );
}

However at runtime when I select the month as 7 and date as 24, the actual values passed to the isLastDayOfMonth fun开发者_Python百科ction are alert("Inside isLastDayOfMonth, the date is " + date ); is 6 and alert("Inside isLastDayOfMonth, the month is " + month ); is 24 and return never seems to be correct.

Please suggest a better approach ..


If you have a JavaScript "Date" object, you can check to see if it's the last day of a month like this:

function isLastDayOfMonth(d) {
  // create a new date that is the next day at the same time
  var nd = new Date(d.getTime());
  nd.setDate(d.getDate() + 1);

  // Check if the new date is in the same month as the passed in date. If the passed in date
  // is the last day of the month, the new date will be "pushed" into the next month.
  return nd.getMonth() === d.getMonth();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜