2012-11-06 16 views
31

Powiel możliwe:
How do I use DateTime.TryParse with a Nullable<DateTime>?Konwersja String do pustych DateTime

mam ten wiersz kodu

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

Czy to jest prawidłowy sposób przekonwertować ciąg pustych DateTime lub czy istnieje bezpośrednia metoda konwersji bez zamiany to do DateTime i ponownie odlewania go do Nullable DateTime?

+1

Możesz rzucić pustą null do nuty DateTime: 'Condition == true? Convert.ToDateTime (stringDate): (DateTime?) Null; ':) – Artemix

+0

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

Odpowiedz

49

Można spróbować to: -

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

Mogę zasugerować' string.IsNullOrEmpty (date) 'zamiast' date == null'. – HackedByChinese

+0

To nie zadziała, jeśli został przekazany łańcuch, który nie był pusty ani data ważna. Aby uzyskać lepsze rozwiązania, zobacz http://stackoverflow.com/questions/192121/how-do-i-using-datetime-tryparse-with-a-nullabledatetime – thelem

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

prostu przypisane bez obsady w ogóle :)

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

Jesteś w stanie zbudować sposób, aby to zrobić:

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

To nie zadziała, ponieważ data nie jest zerową datą zerową. – bret

+0

@bret: Próbowałeś tego? –