Thomas
Thomas

Reputation: 12127

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.

Upvotes: 4

Views: 698

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502816

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.

Upvotes: 11

Related Questions