gpt4 book ai didi

javascript - 验证一个月的最后一个日期

转载 作者:行者123 更新时间:2023-11-28 21:18:30 24 4
gpt4 key购买 nike

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

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("isLastDayOfMonth 内,日期为 "+ date ); 为 6和 alert("在 isLastDayOfMonth 内,月份是 "+ Month ); 是 24并且 return 似乎永远都不正确。

请提出更好的方法..

最佳答案

如果您有一个 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();
}

关于javascript - 验证一个月的最后一个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6985553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com