Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Nullable DateTime [duplicate]

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?

like image 607
Nalaka526 Avatar asked Nov 06 '12 08:11

Nalaka526


People also ask

Can DateTime be null?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.


1 Answers

You can try this:-

 DateTime? dt = string.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date); 
like image 199
Rahul Tripathi Avatar answered Sep 28 '22 14:09

Rahul Tripathi