JS中的Date函数,与设定的日期相比不起作用

Date function in JS, comparing with a set date not working

本文关键字:日期 不起作用 Date 中的 函数 JS      更新时间:2023-09-26

我必须验证并检查用户在ASP中是否未成年。所以1998年7月1日以下的人都是未成年人。我有3个下拉列表来选择日期,月份和年份。我使用JS。我尝试使用concat和split,但他们不工作。有人能帮忙吗?

function ValidateDate() {
    var dDay = document.getElementById('DateList');
    var dMonth = document.getElementById('MonthList');
    var dYear = document.getElementById('YearList');
    var day = dDay.selectedIndex;
    var month = dMonth.selectedIndex;
    var year = dYear.selectedIndex;
    var firstValue = year + month  + day;
    var setyear = "1998";
    var setmonth = "06";
    var setdate = "01";
    var secondValue = setyear + setmonth + setdate;
    var firstDate = new Date();
    firstDate.setFullYear(firstValue[0], (firstValue[1] - 1), firstValue[2]);
    var secondDate = new Date();
    secondDate.setFullYear(secondValue[0], (secondValue[1] - 1), secondValue[2]);
    if (firstDate > secondDate) {
        alert("Pass");
    }
    else {
        alert("Fail");
    }
}
 <asp:CustomValidator ID="CustomValidatorDate" runat="server" 
                        ErrorMessage=" You are underage" CssClass="error" Display="Dynamic" ClientValidationFunction="ValidateDate" ></asp:CustomValidator>

首先,您的日、月和年变量正在读取下拉列表的索引,而不是它们的值。

例如,您需要使用:

var day = dDay.value,
month = dMonth.value,
year = dYear.value;

然后创建date对象为

var firstDate = new Date(year, month, day);

-Dipen