2014-12-27 55 views
6

所以我想弄清楚是否有另一種方法來檢查日期是否有效。所以想法是,如果日期有效,那麼它繼續使用給定的日期,如果日期無效,則使用今天的日期。檢查一個有效日期

這是我的時刻了:

 public void setBirthdate(int year, int month, int day) 
     { 
     if (month < 1 || month > 12 || day < 1 || day > DateTime.DaysInMonth(year, month)) 
     { 
      Birthdate = DateTime.Today; 
     } 
     else 
      Birthdate = new DateTime(year, month, day); 
     } 

那麼,有沒有這樣做的任何較短/更易讀的方式?

在此先感謝

+0

查看'TryParseExact'方法。 – 2014-12-27 18:48:43

+0

DateTime.TryParse – 2014-12-27 18:48:57

+0

使用'try {Birthdate = new DateTime(year,month,day); } catch {Birthdate = DateTime.Today;}' – Avijit 2014-12-27 18:51:37

回答

5

可以使用這些值來嘗試構建一個有效DateTime,再搭上發生的ArgumentOutOfRangeException如果參數超出範圍:

public void setBirthdate(int year, int month, int day) 
{ 
    try 
    { 
     Birthdate = new DateTime(year, month, day); 
    } 
    catch (ArgumentOutOfRangeException) 
    { 
     Birthdate = DateTime.Today; 
    } 
} 

有些人可能會不同意使用這樣的例外,但我只是l在類DateTime做自己的檢查,而不是自己重新創建它們。

documentation,一個ArgumentOutOfRangeException如果發生:

  • 年份大於9999小於1或,或
  • 月是大於12小於1或更大,或
  • 日是少超過1個或大於月份的天數。

或者,你可以從DateTime類複製邏輯:reference

public void setBirthdate(int year, int month, int day) 
{ 
    if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) 
    { 
     int[] days = DateTime.IsLeapYear(year) 
      ? new[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365} 
      : new[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}; 

     if (day >= 1 && day <= days[month] - days[month - 1]) 
      Birthdate = new DateTime(year, month, day); 
    } 
    else 
     Birthdate = DateTime.Today; 
} 
+1

我同意。異常處理有開銷,但你應該總是利用你選擇的框架。它處理你沒有考慮過的邊緣案例的可能性很高。您可以隨時在catch中進行進一步處理,以將值轉向您的用例。 – 2017-07-16 11:46:28

1

試試這個:

public void setBirthdate(int year, int month, int day) 
{ 
    try 
    { 
     Birthdate = new DateTime(year, month, day); 
    } 
    catch (Exception ex) 
    { 
     Birthdate = DateTime.Now; 
    } 
} 
2

我會用在異常TryParseMSDN)方法捕獲(可以是很高的開銷,如果叫經常具有無效值):

DateTime date; 
if (DateTime.TryParse(string.Format("{0}-{1}-{2}", year, month, day), out date)) 
{ 
    // Date was valid. 
    // date variable now contains a value. 
} 
else 
{ 
    // Date is not valid, default to today. 
    date = DateTime.Today; 
} 
+0

就我個人而言,我覺得TryParse的輸出參數更重要,我優化了生產力,所以我使用try/catch並記錄異常。如果輸入中存在反覆出現的問題,我會在對象構造之前添加初始分析。對我來說,異常處理是爲了防止自己陷入不成熟的優化。 – 2017-07-16 11:57:11

0
protected DateTime CheckDate(String date) 
{ 
    DateTime dt; 
try{ 
    dt = DateTime.Parse(date); 

}catch(Exception ex){ 
    dt = DateTime.now(); 
    // may raise an exception 
} 
    finally{ 
     return dt; 
    } 
}