2011-08-08 151 views
0

我有一個計算用戶驗證一個月的最後日期

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 並且返回似乎是不正確的。

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

回答

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(); 
} 
相關問題