How to set DateTime to null

c# entity-framework

Question

Using C#. I have a string dateTimeEnd.

If the string is in right format, I wish to generate a DateTime and assign it to eventCustom.DateTimeEnd of type

public Nullable<System.DateTime> DateTimeEnd { get; set; }

If dateTimeEnd is null or empty I need eventCustom.DateTimeEnd set to null.

I am trying to achieve this using the following code but I get always null for eventCustom.DateTimeEnd.

Could you please help me out to define what is wrong in my code?

   DateTime? dateTimeEndResult;
     if (!string.IsNullOrWhiteSpace(dateTimeEnd))
        dateTimeEndResult = DateTime.Parse(dateTimeEnd);


eventCustom.DateTimeEnd = dateTimeEndResult = true ? (DateTime?)null : dateTimeEndResult;
1
45
5/27/2013 8:32:59 AM

Accepted Answer

It looks like you just want:

eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
    ? (DateTime?) null
    : DateTime.Parse(dateTimeEnd);

Note that this will throw an exception if dateTimeEnd isn't a valid date.

An alternative would be:

DateTime validValue;
eventCustom.DateTimeEnd = DateTime.TryParse(dateTimeEnd, out validValue)
    ? validValue
    : (DateTime?) null;

That will now set the result to null if dateTimeEnd isn't valid. Note that TryParse handles null as an input with no problems.

118
7/1/2015 7:36:47 PM

Popular Answer

DateTime is a non-nullable value type

DateTime? newdate = null;

You can use a Nullable<DateTime>

c# Nullable Datetime



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow