【问题标题】:Correct Date Format Validation of a Date日期的正确日期格式验证
【发布时间】:2014-03-22 06:43:10
【问题描述】:
Label gdate=(Label)(GridView1.Rows[i].FindControl("Date"));

现在我想要确保变量 gdate 中的日期(或值)是一个有效的日期(短日期,如 14-03-2014)没有时间(不像 14-03-2014 00:00:00 这是无效

【问题讨论】:

    标签: c# asp.net date datetime


    【解决方案1】:

    如果需要检查确切的格式,请使用 DateTime TryParseEaxct

    DateTime dateValue
    if (DateTime.TryParseExact(gdate.Text, "dd-MM-yyyy", null, 
                           DateTimeStyles.None, out dateValue))
    {
        //Date in correct format
        //use dateValue
    }
    else
    {
        //Date in incorrect format
    }
    

    Convert.ToDateTime如果无法解析日期时间会抛出异常。

    如果Date 控件中的日期字符串为空,ParseExact 也会抛出异常。

    【讨论】:

    • 不工作!仍在将 gdate.Text 与 dd-MM-yyyy hh:mm:ss 进行比较我只想将 gdate.Text 与 dd-MM-yyyy 进行比较
    • 如果您的日期是这种格式14-03-2014 00:00:00 并且TryParseExact 仅检查dd-MM-yyyy,它肯定不会解析。究竟是什么不工作?
    • 假设这个--> gdate 的值是 20-03-2014,而不是当我根据你给出的代码比较这个值时,它没有得到验证,因为“out dateValue”的格式是 dd -MM-yyyy hh:mm:ss 并且 gdate 的值仅是 dd-MM-yyyy
    • 我只想将 gdate 的值与 dd-MM-yyyy 进行比较
    • out dateValue 是 c# 中所谓的 out 参数。当 TryParseExact() 成功解析您提供给它的字符串时,它会创建一个 DateTime 对象并将其放入dateValue。现在,当您向此函数提供 "14-03-2014" 时,它会正确解析,并且 dateValue 现在将包含一个代表 2014 年 3 月 14 日的 DateTime 对象。现在,这个创建的对象也将有小时分钟和秒全为零,因为这些是它们的默认值值。
    【解决方案2】:

    这里有一个 CustomValidator:

    <asp:CustomValidator runat="server"
        ID="valDateRange" 
        ControlToValidate="txtDatecompleted"
        onservervalidate="valDateRange_ServerValidate" 
        ErrorMessage="enter valid date" />
    

    服务器端:

    protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
    {
        DateTime minDate = DateTime.Parse("1000/12/28");
        DateTime maxDate = DateTime.Parse("9999/12/28");
        DateTime dt;
    
        args.IsValid = (DateTime.TryParse(args.Value, out dt) 
                        && dt <= maxDate 
                        && dt >= minDate);
    }
    

    【讨论】:

      【解决方案3】:

      日期格式可以使用短日期函数,比如

       DateTime dt=new DateTime();
       dt = DateTime.Now;
       MessageBox.Show(dt.ToShortDateString());
      

      【讨论】:

      • 我不是想转换 gdate 的值,我只是想将它与 dd-MM-yyyy 进行比较,甚至与 dd-MM-yyyy hh:mm:ss 进行比较
      【解决方案4】:

      试试这个

      gdate.Text = DateTime.Now.Date.ToShortDateString();
      

      【讨论】:

      • 我不是在尝试转换 gdate 的值,我只是想将它与 dd-MM-yyyy 进行比较,甚至没有与 dd-MM-yyyy hh:mm:ss 进行比较
      【解决方案5】:

      试试这个来存储格式化日期

      string chkin = txtCheckIn.Text;
      DateTime CheckIn = DateTime.ParseExact(chkin, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
      

      【讨论】:

        猜你喜欢
        • 2017-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-27
        相关资源
        最近更新 更多