46

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?

Community
  • 1
  • 1
Nalaka526
  • 11,278
  • 21
  • 82
  • 116

4 Answers4

81

You can try this:-

 DateTime? dt = string.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 4
    I might suggest `string.IsNullOrEmpty(date)` rather than `date == null`. – moribvndvs Nov 06 '12 at 08:41
  • 3
    That wouldn't work if a string that was neither empty nor a valid date was passed. For better solutions see http://stackoverflow.com/questions/192121/how-do-i-use-datetime-tryparse-with-a-nullabledatetime – thelem Aug 07 '14 at 15:49
16

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;
}
cuongle
  • 74,024
  • 28
  • 151
  • 206
3
DateTime? dt = (String.IsNullOrEmpty(stringData) ? (DateTime?)null : DateTime.Parse(dateString));
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
1

Simply assigned without cast at all :)

DateTime? dt = Condition == true ? Convert.ToDateTime(stringDate) : null;
Han
  • 3,272
  • 3
  • 24
  • 39