2012-11-06 42 views
31

可能重複:
How do I use DateTime.TryParse with a Nullable<DateTime>?字符串轉換爲可空的DateTime

我有這行代碼

DateTime? dt = Condition == true ? (DateTime?)Convert.ToDateTime(stringDate) : null; 

這是一個字符串轉換爲可空的DateTime的正確方法,還是有沒有直接的方法轉換轉換它到DateTime並再次鑄造它爲可空日期時間?

+1

您可以將null轉換爲可爲空的DateTime:'Condition == true? Convert.ToDateTime(stringDate):(DateTime?)null;':) – Artemix

+0

'DateTime? dt = dt.GetValueOrDefault(DateTime.Now);' – Jnr

回答

49

你可以試試這個: -

DateTime? dt = string.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date); 
+2

我可能會建議'string.IsNullOrEmpty(date)'而不是'date == null'。 – HackedByChinese

+0

如果一個既不是空也不是有效日期的字符串被傳遞,那麼這將不起作用。爲更好的解決方案請參閱http://stackoverflow.com/questions/192121/how-do-i-use-datetime-tryparse-with-a-nullabledatetime – thelem

3
DateTime? dt = (String.IsNullOrEmpty(stringData) ? (DateTime?)null : DateTime.Parse(dateString)); 
1

只需在不投全部劃歸:)

DateTime? dt = Condition == true ? Convert.ToDateTime(stringDate) : null; 
11

您能夠建立這樣做的方法:

public static DateTime? TryParse(string stringDate) 
{ 
    DateTime date; 
    return DateTime.TryParse(stringDate, out date) ? date : (DateTime?)null; 
} 
+2

這將無法正常工作,因爲日期不是可空的日期時間。 – bret

+0

@bret:你試過這個嗎? –