【问题标题】:How to Validate a DateTime in C#?如何在 C# 中验证日期时间?
【发布时间】:2010-09-27 04:25:42
【问题描述】:

我怀疑我是唯一提出此解决方案的人,但如果您有更好的解决方案,请在此处发布。我只是想把这个问题留在这里,以便我和其他人以后可以搜索它。

我需要判断是否在文本框中输入了有效日期,这是我想出的代码。当焦点离开文本框时我会触发它。

try
{
    DateTime.Parse(startDateTextBox.Text);
}
catch
{
    startDateTextBox.Text = DateTime.Today.ToShortDateString();
}

【问题讨论】:

  • 从答案来看,我认为我应该使用 TryParse 感谢各位的出色回答。我什至没有想过 TryParse
  • 一个简单的谷歌问题示例,如果今天有人问,会因为“没有足够的研究”而被不公平地关闭。
  • 这是一种无需使用任何特殊功能的简单方法:stackoverflow.com/questions/14917203/…>
  • 使用 DateTimes 总是让贝司感到痛苦。谢谢

标签: c# datetime validation


【解决方案1】:
DateTime.TryParse

我相信这更快,这意味着你不必使用丑陋的 try/catch :)

例如

DateTime temp;
if(DateTime.TryParse(startDateTextBox.Text, out temp))
{
  // Yay :)
}
else
{
  // Aww.. :(
}

【讨论】:

  • 如果我错了,请纠正我,但在 C#(与 JavaScript 相对)中,if/else 分支不需要大括号吗?不要误会我的意思,我不是要仔细检查,这是一个很棒的答案,我 +1 是因为它对我有帮助,但只是想,因为在查看已经发布的答案时,你永远不知道未来的新用户有多新,这个可以迷惑他们。当然,如果您在 C# 中遇到花括号问题,那么这个问题将是您最不必担心的问题...
  • @VoidKing 您对花括号是正确的,但如果您在该块中只有 1 条语句,则不必使用它们。这也适用于其他一些语言,但我可以看到这会如何误导新的编码人员。
  • @D.Galvez 对不起,我迟到了,但是即使只有 1 条语句,最好也包括括号?这可能只是个人偏好最重要的情况——在这种情况下,我发现包括它们对于可读性和一致性来说非常好。
  • 6年前我不知道会发生这样一场关于括号的辩论。
  • 可以用if(DateTime.TryParse(startDateTextBox.Text, out var temp))缩短变量初始化:)
【解决方案2】:

不要将异常用于流控制。使用DateTime.TryParseDateTime.TryParseExact。就我个人而言,我更喜欢具有特定格式的 TryParseExact,但我想有时候 TryParse 会更好。基于您的原始代码的示例使用:

DateTime value;
if (!DateTime.TryParse(startDateTextBox.Text, out value))
{
    startDateTextox.Text = DateTime.Today.ToShortDateString();
}

选择这种方法的原因:

  • 更清晰的代码(它说明了它想要做什么)
  • 比捕获和吞咽异常更好的性能
  • 这不会不恰当地捕获异常 - 例如OutOfMemoryException,线程中断异常。 (您当前的代码可以通过捕获相关异常来避免这种情况,但使用 TryParse 仍然会更好。)

【讨论】:

    【解决方案3】:

    这是解决方案的另一种变体,如果字符串可以转换为 DateTime 类型,则返回 true,否则返回 false。

    public static bool IsDateTime(string txtDate)
    {
        DateTime tempDate;
        return DateTime.TryParse(txtDate, out tempDate);
    }
    

    【讨论】:

    • 欢迎来到 StackOverflow!请查看已经提供的答案,尤其是在回答超过三年且已成功回答的问题时。您的答案已经被之前的受访者覆盖了。
    【解决方案4】:

    【讨论】:

      【解决方案5】:

      使用TryParse怎么样?

      【讨论】:

        【解决方案6】:

        使用DateTime.TryParse 的一个问题是它不支持非常常见的数据输入用例,即输入不带分隔符的日期,例如011508.

        这是一个如何支持这一点的示例。 (这是来自我正在构建的一个框架,所以它的签名有点奇怪,但核心逻辑应该是可用的):

            private static readonly Regex ShortDate = new Regex(@"^\d{6}$");
            private static readonly Regex LongDate = new Regex(@"^\d{8}$");
        
            public object Parse(object value, out string message)
            {
                msg = null;
                string s = value.ToString().Trim();
                if (s.Trim() == "")
                {
                    return null;
                }
                else
                {
                    if (ShortDate.Match(s).Success)
                    {
                        s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 2);
                    }
                    if (LongDate.Match(s).Success)
                    {
                        s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 4);
                    }
                    DateTime d = DateTime.MinValue;
                    if (DateTime.TryParse(s, out d))
                    {
                        return d;
                    }
                    else
                    {
                        message = String.Format("\"{0}\" is not a valid date.", s);
                        return null;
                    }
                }
        
            }
        

        【讨论】:

        • 我并不担心分隔符,因为我使用的是蒙版文本框,但我可以看到在我使用此应用程序可能遇到的其他情况下它会很方便。
        • 为什么使用不带分隔符的 DateTime 字符串?
        【解决方案7】:

        一个班轮:

        if (DateTime.TryParse(value, out _)) {//dostuff}
        

        【讨论】:

          【解决方案8】:
              protected bool ValidateBirthday(String date)
              {
                  DateTime Temp;
          
                  if (DateTime.TryParse(date, out Temp) == true &&
                Temp.Hour == 0 &&
                Temp.Minute == 0 &&
                Temp.Second == 0 &&
                Temp.Millisecond == 0 &&
                Temp > DateTime.MinValue)
                      return true;
                  else
                      return false;
              }
          

          //假设输入字符串为短日期格式。
          例如"2013/7/5" 返回 true 或
          “2013/2/31”返​​回假。
          http://forums.asp.net/t/1250332.aspx/1
          //bool booleanValue = ValidateBirthday("12:55");返回错误

          【讨论】:

            【解决方案9】:
            private void btnEnter_Click(object sender, EventArgs e)
            {
                maskedTextBox1.Mask = "00/00/0000";
                maskedTextBox1.ValidatingType = typeof(System.DateTime);
                //if (!IsValidDOB(maskedTextBox1.Text)) 
                if (!ValidateBirthday(maskedTextBox1.Text))
                    MessageBox.Show(" Not Valid");
                else
                    MessageBox.Show("Valid");
            }
            // check date format dd/mm/yyyy. but not if year < 1 or > 2013.
            public static bool IsValidDOB(string dob)
            { 
                DateTime temp;
                if (DateTime.TryParse(dob, out temp))
                    return (true);
                else 
                    return (false);
            }
            // checks date format dd/mm/yyyy and year > 1900!.
            protected bool ValidateBirthday(String date)
            {
                DateTime Temp;
                if (DateTime.TryParse(date, out Temp) == true &&
                    Temp.Year > 1900 &&
                   // Temp.Hour == 0 && Temp.Minute == 0 &&
                    //Temp.Second == 0 && Temp.Millisecond == 0 &&
                    Temp > DateTime.MinValue)
                    return (true);
                else
                    return (false);
            }
            

            【讨论】:

              【解决方案10】:

              您还可以为特定的CultureInfo 定义DateTime 格式

              public static bool IsDateTime(string tempDate)
              {
                  DateTime fromDateValue;
                  var formats = new[] { "MM/dd/yyyy", "dd/MM/yyyy h:mm:ss", "MM/dd/yyyy hh:mm tt", "yyyy'-'MM'-'dd'T'HH':'mm':'ss" };
                  return DateTime.TryParseExact(tempDate, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDateValue);
              }
              

              【讨论】:

                【解决方案11】:

                所有答案都非常好,但是如果您想使用单个功能,这可能会起作用。 它将与其他日期格式一起使用,但不适用于此日期,例如:05/06/202 它会将其视为有效日期,但不是。

                private bool validateTime(string dateInString)
                {
                    DateTime temp;
                    if (DateTime.TryParse(dateInString, out temp))
                    {
                       return true;
                    }
                    return false;
                }
                

                【讨论】:

                • 返回 DateTime.TryParse() 的结果而不是 "if" 块怎么样?此外,您的 IDE 会抱怨从未使用过的 temp,您可以在函数调用中直接将其声明为“out DateTime temp”。
                【解决方案12】:
                DateTime temp;
                try
                {
                    temp = Convert.ToDateTime(grd.Rows[e.RowIndex].Cells["dateg"].Value);
                    grd.Rows[e.RowIndex].Cells["dateg"].Value = temp.ToString("yyyy/MM/dd");
                }
                catch 
                {   
                    MessageBox.Show("Sorry The date not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop,MessageBoxDefaultButton.Button1,MessageBoxOptions .RightAlign);
                    grd.Rows[e.RowIndex].Cells["dateg"].Value = null;
                }
                

                【讨论】:

                • 你必须通过 try catch 检查是否有效。因此,您可以使用 try catch 来检查所有类型的变量并制作有效的全局函数并控制项目中的所有内容。最好的问候..... Ashraf khalifah
                【解决方案13】:
                DateTime temp;
                try
                {
                    temp = Convert.ToDateTime(date);
                    date = temp.ToString("yyyy/MM/dd");
                }
                catch 
                {
                    MessageBox.Show("Sorry The date not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop,MessageBoxDefaultButton.Button1,MessageBoxOptions .RightAlign);
                    date = null;
                }
                

                【讨论】:

                  【解决方案14】:
                  protected static bool CheckDate(DateTime date)
                  {
                      if(new DateTime() == date)      
                          return false;       
                      else        
                          return true;        
                  } 
                  

                  【讨论】:

                  • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
                  • 问题是询问如何验证可能包含或不包含 DateTIme 值的 string。您正在检查给定的DateTime 是否具有默认值(对应于0001-01-01T00:00:00.0000000)。这如何回答这个问题?
                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2015-07-18
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-06-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多