Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert System.DateTime to NodaTime.ZonedDateTime

Tags:

c#

nodatime

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?

like image 274
ConditionRacer Avatar asked Sep 13 '16 17:09

ConditionRacer


1 Answers

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
like image 184
stephen.vakil Avatar answered Oct 15 '22 03:10

stephen.vakil