Converting Nullable DateTime

Today at work we ran into an issue where we needed to convert nullable DateTime values to UTC time values. Of course this can’t be done if there isn’t a value present. Most programmers first thought is to wrap this in an “if” statement. There is a much easier way. Here is a code example:

DateTime? testDate = DateTime.Now;

DateTime? newDate = testDate.HasValue ? TimeZoneInfo.ConvertTimeToUtc(testDate.Value) : testDate;

With this code, if there is a local time value, it will be converted with no Exceptions being thrown.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

2 thoughts on “Converting Nullable DateTime

  1. Hello.
    Would you mind letting me know which webhost you’re utilizing? I’ve
    loaded your blog in 3 different internet browsers and I must say this blog loads a lot faster then most.
    Can you recommend a good hosting provider at a fair price?

    Thanks, I appreciate it!

Leave a reply to Monserrate Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.