Convert DateTime with DateTimeKind.Unspecified from utc to local

I have a database where all dates are UTC, and the driver always sends me DateTime objects with DateTimeKind.Unspecified. I want to assume they are in UTC and convert to local time.

What is the simplest way to achieve this using NodaTime?

Instant.FromDateTimeUtc(utcDate).InZone(localZone); keeps complaining DateTimeKind should be Utc.

Jon Skeet
people
quotationmark

If you're definitely using Noda Time and want a ZonedDateTime, you could "tell" Noda Time that you've really got a UTC value, then convert it:

var zoned = LocalDateTime.FromDateTime(utcDate)
                         .InZoneStrictly(DateTimeZone.Utc)
                         .WithZone(localZone);

Or you could just use DateTime.SpecifyKind to start with:

var utcDateTime = DateTime.SpecifyKind(unspecifiedDateTime, DateTimeKind.Utc);

... and then use your existing code, or take Noda Time out of the picture entirely if you want.

Indeed, just DateTime.ToLocalTime() would be fine if you don't need Noda Time elsewhere:

var localDateTime = utcDateTime.ToLocalTime();

... the BCL will assume that an unspecified date/time is UTC if you call ToLocalTime() on it. Of course, I'd recommend using Noda Time everywhere though :)

people

See more on this question at Stackoverflow