日期函数不能正常工作

date function not working proprly

本文关键字:工作 常工作 函数 不能 日期      更新时间:2024-01-09

在我的asp网页中,我使用ajax日历来选择日期。我不想让用户选择过去的日期或当前日期,或者从当前日期起超过20天。

var today = new Date();
            var twentyDays = new Date();
            twentyDays.setDate(today.getDate() + 20);
            if (selectedDate.getDateOnly() <= todayDate.getDateOnly())
            {
                alert('Date Cannot be in the past or current date');
                sender._textbox.set_Value(null);
            }
            else if (selectedDate.getDateOnly() > twentyDays.getDateOnly())
            {
                alert('this is more than 20 days');
                sender._textbox.set_Value(null);
                return;
            }

但它没有比较日期。。这是我的asp代码

<asp:TextBox ID="txtDate" runat="server" ></asp:TextBox>
<asp:ImageButton ID="imgCalender" runat="server" ImageUrl="~/Images/Calendar.png" ToolTip="Select a Date" />
 <asp:CalendarExtender ID="calShow"  runat="server" PopupButtonID="imgCalender" PopupPosition="BottomLeft" TargetControlID="txtDate" OnClientDateSelectionChanged="CheckForPastDate"></asp:CalendarExtender>

试着去掉getDateOnly(),据我所知,它不是javascript Date对象的一部分,并使用getTime()

我建议使用服务器端逻辑来处理这一问题,而不是JavaScript,因为当日期导致日期与今天不在同一年(即一年的12月30日)时,today.getDate() + 20将不起作用。

相反,使用.NET Framework的DateTime对象来添加天数,并通过ASP.NET AJAX页面方法进行比较,如下所示:

代码背后:

[WebMethod]
public static string CompareDate(string theDateToCompare)
{
    DateTime dateValue;
    if (DateTime.TryParse(dateString, out dateValue))
    { 
        DateTime today = DateTime.Now;
        DateTime twentyDaysFromNow = today.AddDays(20);
        if(dateValue <= today)
        {
            return "Date cannot be in the past or current date"; 
        }
        else if (dateValue > twentyDaysFromNow)
        {
            return "Date cannot be more than 20 days in the future";
        }
    }
    else
    {
        return "Unable to parse " + dateString; 
    }
}

标记:

$(document).ready(function() {
    // Add selector event here to trigger call to server side
    $.ajax({
        type: "POST",
        url: "PageName.aspx/CompareDate",
        data: "{'CompareDate':'11/30/2013'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            if (result.hasOwnProperty("d")) {
                // The .d is part of the result so reference it
                //  to get to the actual JSON data of interest
                alert(result.d);
            }
            else {
                // No .d; so just use result
                alert(result);
            }
       }
    });
});

注意:您需要将PageName.aspx的名称更改为.aspx页面的名称。此外,.d语法是微软在ASP.NET AJAX的ASP.NET 3.5版本中引入的反XSS保护;因此检查CCD_ 9属性是否存在。