Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NodaTime, how to convert an Instant to the corresponding system's ZonedDateTime?

Tags:

c#

.net

nodatime

I have an event log in a database with the events' datetime stored as UTC time. In my application, where I'm using NodaTime, I get the value as a DateTime and then convert it to an Instant:

var instant = NodaTime.Instant.FromDateTimeUtc(DateTime.SpecifyKind(eventDateTime, DateTimeKind.Utc));

Now I want to get the ZonedDateTime corresponding to instant using the system's time zone. I know I can use instant.InZone(systemTimeZone) to get the ZonedDateTime I need. However, I don't know how to populate the systemTimeZone variable with the correct value. How can I get the DateTimeZone object corresponding to the system's time zone?

like image 231
MarioVW Avatar asked Dec 27 '13 21:12

MarioVW


1 Answers

Use IDateTimeZoneProvider.GetSystemDefault for the time zone provider you're interested in. For example:

var systemZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
var zonedDateTime = instant.InZone(systemZone);

Or use DateTimeZoneProviders.Bcl to use the appropriate TimeZoneInfo-backed time zone.

like image 71
Jon Skeet Avatar answered Sep 20 '22 23:09

Jon Skeet