Search code examples
c#datetimemodel-view-controllernullablenull-coalescing-operator

How to cast a nullable DateTime to UTC DateTime


I'm reading back a DateTime? value from my view. Now I check to see if the NextUpdate DateTime? HasValue and if so convert that time to UTC.

From reading up on this it seems I need to use a null coalescing operator but my assignment tells me that System.NUllable does not contain a definition for ToUniversalTime() when using that operator.

I've searched on SO for a similar question but no luck on that.

Question:

How can I convert a null DateTime value to UTC?

Code:

I'm simply checking if the DateTime? has a value, and if so convert that DateTie to UTC -

            if (escalation.NextUpdate.HasValue)
            { 
                escalation.NextUpdate = escalation.NextUpdate ?? escalation.NextUpdate.ToUniversalTime(); 
            }
            else
            {
                escalation.NextUpdate = null;
            }

My NextUpdate property in the model:

    public DateTime? NextUpdate { get; set; }

Solution

  • Your code is wrong in more than one way.

    The ?? operator returns the left side if it is not null, otherwise the right side.
    Since you already checked that escalation.NextUpdate.HasValue is true, the left side is not null and you assign the same date again (without converting to UTC).

    Nullable<DateTime> does not declare ToUniversalTime(), you need to do that on the value.

    So the final code should look like this:

    if (escalation.NextUpdate.HasValue)
        escalation.NextUpdate = escalation.NextUpdate.Value.ToUniversalTime(); 
    

    or with C#6

    escalation.NextUpdate = escalation.NextUpdate?.ToUniversalTime();
    

    There is no need for the else branch as in that case it would be null anyway.