2012-11-06 36 views
31

Olası Çoğalt:
How do I use DateTime.TryParse with a Nullable<DateTime>?dönüştürme Dize

Ben bu kod satırı var

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

bu null DateTime için dize dönüştürmek için doğru yolu var mı veya dönüştürmedendönüştürmek için doğrudan bir yöntem var mı, DateTime'a ve null NULLLible DateTime'a döküm mü?

+1

Null'ı boş bırakılabilir DateTime: 'Koşul == true? Convert.ToDateTime (stringDate): (DateTime?) Null; ':) – Artemix

+0

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

cevap

49

Bu deneyebilirsiniz: -

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

' date == null' yerine string.IsNullOrEmpty (tarih) 'ı önerebilirim. – HackedByChinese

+0

Boş olmayan bir dize veya geçerli bir tarih geçtiyse bu işe yaramaz. Daha iyi çözümler için 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

Basitçe de döküm olmadan atanan tüm Bunu yapmak için bir yöntem inşa edebiliyoruz :)

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

adresine bakın. Bu tarih, null olmayan bir tarih değil olduğundan çalışmayacaktır. – bret

+0

Bret: Bunu denedin mi? –