在asp.net中比较日期和今天

本文关键字:日期 今天 比较 asp net | 更新日期: 2023-09-27 18:04:40

我有一个从用户输入日期的textbox。现在我想做一个validator,它检查日期是否大于今天。

我尝试了这个链接,但是它有一些问题http://forums.asp.net/t/1116715.aspx/1

如果我给这个日期 25/03/2013 它是正确的,但如果给 01/04/2013 ,它说它比今天少。

* *

<asp:CompareValidator ID="CompareValidator2" runat="server" ControlToValidate="txtReturnDate"
                                Display="Dynamic" ErrorMessage="Date should be greater then  today" ForeColor="Red"
                                Operator="GreaterThan" ValidationGroup="VI">Date should be greater then  today</asp:CompareValidator>
* *

请帮我解决这个问题

在asp.net中比较日期和今天

使用下面的代码比较指定的日期和今天的日期

string date = "01/04/2013";
                DateTime myDate = DateTime.ParseExact(date, "dd/MM/yyyy",
                                           System.Globalization.CultureInfo.InvariantCulture);
                if (myDate > DateTime.Today)
                {
                    Console.WriteLine("greater than");
                }
               else
                {
                 Console.WriteLine("Less Than");
                }

好的,我已经完成了

CompareValidator1.ValueToCompare = DateTime.Today.ToString("MM/dd/yyyy");

问题是25/3/2013无疑是25th March 2013,然而,错误的文化设置,01/04/13可能是4th january 2013,这确实是在今天的日期之前。我猜你以为你进入的是1st April 2013,它会在。

解是

之一
  • 在文本框中输入时使用明确的日期格式(2013-01-04为4月1日)
  • 使用一个公开实际日期的日期选择器组件
  • 按您期望的方式解析日期(dd/MM/yyyy)

asp:CompareValidator的问题是,它似乎不明白日期可以不同的格式,并使用DateTimeToShortDateString变体来比较(谁实现这应该被枪杀!)。根据这个问题的解决方案似乎是使用CustomValidator

protected void DateTimeComparision_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = DateTime.ParseExact(txtDate.Text,"dd/MM/yyyy") > DateTime.Today 
}

它认为1/4/2013是1月4日。你应该使用新的DateTime(年,月,日)构造函数创建一个DateTime对象,这样比较就能正常工作,即

var compareDate = new DateTime(2013,4,1)
bool afterToday = DateTime.Today < compareDate

这种类型的日期验证应该在客户端执行。在我的应用程序中,我们使用了以下代码

convert: function (d) {
        /* Converts the date in d to a date-object. The input can be:
        a date object: returned without modification
        an array      : Interpreted as [year,month,day]. NOTE: month is 0-11.
        a number     : Interpreted as number of milliseconds
        since 1 Jan 1970 (a timestamp) 
        a string     : Any format supported by the javascript engine, like
        "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
        an object     : Interpreted as an object with year, month and date
        attributes.  **NOTE** month is 0-11. */
        return (
        d.constructor === Date ? d :
        d.constructor === Array ? new Date(d[0], d[1], d[2]) :
        d.constructor === Number ? new Date(d) :
        d.constructor === String ? new Date(d) :
        typeof d === "object" ? new Date(d.year, d.month, d.date) :
        NaN
    );
 isFutureDate: function (a) {
        var now = new Date();
        return (a > now) ? true : false;
    },

现在像这样调用上面的函数(isFutureDate(convert("your form date value")))