问题
Possible Duplicate:
How do I use DateTime.TryParse with a Nullable<DateTime>?
I have this line of code
DateTime? dt = Condition == true ? (DateTime?)Convert.ToDateTime(stringDate) : null;
Is this the correct way to convert string to Nullable DateTime, or is there a direct method to convert without converting it to DateTime and again casting it to Nullable DateTime?
回答1:
You can try this:-
DateTime? dt = string.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date);
回答2:
You are able to build a method to do this:
public static DateTime? TryParse(string stringDate)
{
DateTime date;
return DateTime.TryParse(stringDate, out date) ? date : (DateTime?)null;
}
回答3:
DateTime? dt = (String.IsNullOrEmpty(stringData) ? (DateTime?)null : DateTime.Parse(dateString));
回答4:
Simply assigned without cast at all :)
DateTime? dt = Condition == true ? Convert.ToDateTime(stringDate) : null;
来源:https://stackoverflow.com/questions/13247273/convert-string-to-nullable-datetime