Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime + TZ -> NodaTime conversion

Tags:

c#

nodatime

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.

like image 638
Thomas Avatar asked Dec 18 '22 23:12

Thomas


1 Answers

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.
like image 200
Jon Skeet Avatar answered Jan 03 '23 06:01

Jon Skeet