验证一个月的最后日期

时间:2011-08-08 16:48:26

标签: javascript

我有两个函数来计算用户输入的月份的最后日期

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

但是在运行时我选择月份为7,日期为24, 传递给isLastDayOfMonth函数的实际值是 alert("Inside isLastDayOfMonth, the date is " + date );是6 而alert("Inside isLastDayOfMonth, the month is " + month );是24 并且返回似乎永远不正确。

请建议更好的方法..

1 个答案:

答案 0 :(得分:3)

如果你有一个JavaScript“日期”对象,你可以查看它是否是一个月的最后一天:

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