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;
Share:
62,338
Nalaka526
Author by

Nalaka526

Updated on July 09, 2022

Comments

  • Nalaka526
    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
    moribvndvs over 11 years
    I might suggest string.IsNullOrEmpty(date) rather than date == null.
  • bret
    bret over 10 years
    This won't work since date is not a nullable datetime.
  • cuongle
    cuongle over 10 years
    @bret: Did you try this?
  • thelem
    thelem almost 10 years
    That wouldn't work if a string that was neither empty nor a valid date was passed. For better solutions see stackoverflow.com/questions/192121/…