Convert String to Nullable DateTime
62,338
Solution 1
You can try this:-
DateTime? dt = string.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date);
Solution 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;
}
Solution 3
DateTime? dt = (String.IsNullOrEmpty(stringData) ? (DateTime?)null : DateTime.Parse(dateString));
Solution 4
Simply assigned without cast at all :)
DateTime? dt = Condition == true ? Convert.ToDateTime(stringDate) : null;
Author by
Nalaka526
Updated on July 09, 2022Comments
-
Nalaka526 almost 2 years
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?
-
moribvndvs over 11 yearsI might suggest
string.IsNullOrEmpty(date)
rather thandate == null
. -
bret over 10 yearsThis won't work since date is not a nullable datetime.
-
cuongle over 10 years@bret: Did you try this?
-
thelem almost 10 yearsThat wouldn't work if a string that was neither empty nor a valid date was passed. For better solutions see stackoverflow.com/questions/192121/…