簡體   English   中英

驗證一個月的最后日期

[英]Validating the last date of a month

我有兩個函數來計算用戶輸入的月份的最后日期

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,返回似乎永遠都不正確。

請提出一個更好的方法..

如果您有一個JavaScript“ Date”對象,則可以檢查是否是一個月的最后一天,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM