Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
like image 629
Brian Var Avatar asked Jun 02 '16 10:06

Brian Var


2 Answers

if you are using c#6 then its very simple

escalation.NextUpdate?.ToUniversalTime();

this translates as if NextUpdate is not null call ToUniversalTime() else return null

if you can't use c#6 then inline if is probably your best bet

escalation.NextUpdate.HasValue ? (DateTime?)escalation.NextUpdate.Value.ToUniversalTime():null;

this is basically the same as your full if baring you've missed out the Value property of the nullable and corrects your use of the ?? operator

like image 39
MikeT Avatar answered Oct 11 '22 15:10

MikeT


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.

like image 166
René Vogt Avatar answered Oct 11 '22 14:10

René Vogt