11

I have a System.DateTime which is already in a specific timezone but does not specify a DateTime.Kind, and a string that represents an IANA timezone. I want to convert this to a NodaTime.ZonedDateTime.

For example:

var original = new DateTime(2016, 1, 1, 12, 0, 0);
var timezone = "America/Chicago";

I want a ZonedDateTime that represents 01/01/2016 - 12PM in Chicago time. How do I do this?

ConditionRacer
  • 4,418
  • 6
  • 45
  • 67

1 Answers1

15

If I understand you correctly, you want to take a standard DateTime with a known time in Chicago and get a ZonedDateTime representing this Date + Time + Time Zone, correct?

If so, I believe this will do it. The intermediate conversion from DateTime to LocalDateTime might not be necessary if you can construct it directly.

var dotNetDateTime = new DateTime(2016, 1, 1, 12, 0, 0);
var localDate = LocalDateTime.FromDateTime(dotNetDateTime);
var chicagoTime = DateTimeZoneProviders.Tzdb["America/Chicago"];
var chicagoZonedDateTime = chicagoTime.AtStrictly(localDate); // Will contain 2016 01 01 noon

// now you can convert to time in Los Angeles
var laTime = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
var laZonedDateTime = chicagoZonedDateTime.WithZone(laTime); // will contain 2016 01 01 10am
stephen.vakil
  • 3,492
  • 1
  • 18
  • 23
  • 3
    Yes, this is right - but also you might consider that `AtStrictly` may or may not have the behavior you're looking for. Good to get familiar with the other options such as `AtLeniently`, and custom resolvers such as the [scheduling resolver I show here](http://stackoverflow.com/a/25124701/634824), (which is the new lenient resolver in 2.x). – Matt Johnson-Pint Sep 13 '16 at 21:47