2008-12-16 96 views
89

我怀疑我是唯一一个提出这个解决方案的人,但是如果您有更好的解决方案,请在此发布。我只想在此留下这个问题,以便我和其他人稍后可以搜索它。验证C#中的日期时间#

我需要告诉一个有效的日期是否已经输入到一个文本框中,这是我想出的代码。当焦点离开文本框时我开始播放。

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

的答案来看,我想我应该用的TryParse为伟大的答案家伙 感谢。我甚至没有想过TryParse – Matt 2008-12-16 18:17:33

+1

一个易于谷歌问题的例子,如果有人问今天会因“没有足够的研究”而不公平地关闭。 – 2013-06-27 20:39:56

+1

这里是一个简单的方法来做到这一点,而不使用任何特殊的功能: xameeramir 2013-09-11 16:20:15

回答

198
DateTime.TryParse 

我相信这是更快,这意味着你不必使用难看的try /渔获:)

DateTime temp; 
if(DateTime.TryParse(startDateTextBox.Text, out temp)) 
//yay 
else 
// :(
53

请勿将异常用于流量控制。使用DateTime.TryParseDateTime.TryParseExact。我个人更喜欢TryParseExact与特定的格式,但我想有些时候TryParse更好。

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

理由喜欢这种方法:

  • 更清晰的代码(它说什么做就是了),比捕捉和吞咽异常
  • 更好的性能,根据您的原始代码示例使用
  • 这不会不恰当地捕捉异常 - 例如OutOfMemoryException,ThreadInterruptedException。 (您的当前代码可以通过仅捕获相关异常来解决,但使用TryParse仍然会更好。)
3

使用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; 
      } 
     } 

    } 
12

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

public static bool IsDateTime(string txtDate) 
{ 
    DateTime tempDate; 
    return DateTime.TryParse(txtDate, out tempDate); 
} 
1
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”返​​回false。
http://forums.asp.net/t/1250332.aspx/1
// bool booleanValue = ValidateBirthday(“12:55”);返回false

1
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); 
} 
-3
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; 
} 
-3
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; 
}