2008-12-16 95 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; 
}