2012-11-06 4 views
31

가능한 중복 :
How do I use DateTime.TryParse with a Nullable<DateTime>?변환 문자열

내가 코드 줄을

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

이 Null 허용 날짜 시간에 문자열을 변환하는 올바른 방법인가 또는 을로 변환하지 않고 직접 변환 할 수있는 방법이 있습니까?DateTime으로 다시 캐스팅 Nullable DateTime으로 변환 하시겠습니까?

+1

null을 nullable로 변환 할 수 있습니다. 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

'date == null 대신'string.IsNullOrEmpty (date)'를 제안 할 수도 있습니다. – 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

날짜가 null 입력 가능 날짜가 아니기 때문에이 방법은 작동하지 않습니다. – bret

+0

@bret : 이것을 시도 했습니까? –