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.

Advertisements

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s