DateTime + TZ > NodaTime conversion

When I look about how to convert time to NodaTime, I find many posts but not a single straight answer about what I need.

I have:

- A DateTime object (DateTime myDateTime)
- An Olson timezone (var TZ = "America/Los_Angeles")

I want:

- A ZonedDateTime object (ZonedDateTime myZonedDateTime)

Ideally, I'm looking for some helper like:

var myZonedDateTime = ZonedDateTime.From(myDateTime, TZ);

but all the samples I see go through turning the date into a string and then parsing the string, which seems quite odd.

There is a ZonedDateTime.FromDateTimeOffset() method, but the offset and the TimeZone are different things since the TZ can handle daylight savings.

Jon Skeet
people
quotationmark

It sounds like you just want:

var local = LocalDateTime.FromDateTime(myDateTime);
var zone = DateTimeZoneProviders.Tzdb[id];
var zoned = local.InZoneLeniently(zone);

Except:

  • You may well want to write your own rules instead of using InZoneLeniently
  • You may want to use DateTimeZoneProviders.Tzdb.GetZoneOrNull(id) if you're not sure whether the zone ID will be recognized by Noda Time.

people

See more on this question at Stackoverflow