Convert String to Nullable DateTime

Nalaka526 picture Nalaka526 · Nov 6, 2012 · Viewed 57.2k times · Source

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?

Answer

Rahul Tripathi picture Rahul Tripathi · Nov 6, 2012

You can try this:-

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