Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime to LocalDate (NodaTime)

I have a DateTime that needs to be converted to a NodaTime LocalDate. Can this be done?

I have this:

 DateTime modifiedDate = File.GetLastWriteTime(file);

And I want this:

LocalTime modifiedDate = File.GetLastWriteTime(file);

But it looks like NodaTime API can not get a date value from GetLastWriteTime.

So I either need to a) Convert the DateTime to LocalTime or b) somehow use LocalTime to get a date value from GetLastWriteTime

like image 537
user2475310 Avatar asked Apr 16 '14 20:04

user2475310


1 Answers

One of the principle design decisions of Noda Time, is that there should be no side-effects created by local time zone setting of the computer. Internally, GetLastWriteTime calls GetLastWriteTimeUtc().ToLocalTime(). So just by calling GetLastWriteTime, you are violating this ideal.

The correct Noda Time type to read a file time would be an Instant.

Instant instant = Instant.FromDateTimeUtc(File.GetLastWriteTimeUtc(file));

From there, if you desire a local date and/or time, then you can apply a time zone.

First, decide what time zone you want. For example:

DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/New_York"];

If you want for some reason to use the computer's own local time zone, then use this:

DateTimeZone zone = DateTimeZoneProviders.Tzdb.GetSystemDefault();

Then apply the time zone to the instant of your file time:

ZonedDateTime zonedDateTime = instant.InZone(zone);

Then you can pick from any of these, depending on what exactly you're looking for:

LocalDateTime localDateTime = zonedDateTime.LocalDateTime;
LocalDate date = zonedDateTime.Date;
LocalTime time = zonedDateTime.TimeOfDay;

Also, you should understand that on disk, the file time is dependent on the type of file system you're working with.

  • If you are working with NTFS, the time on disk is recorded in UTC. This is highly desired.

  • If you are working with exFAT, the time on disk is recorded in local date + time, but it also includes the offset from UTC, so it is easily translated back to UTC without ambiguity.

  • If you are working with FAT or FAT32 file systems, the time on disk is recorded using the local time, by the time zone that's in effect when the file is written.

    This creates ambiguous data, as you might be writing to a file during a daylight saving time fall-back transition, or you might be reading the data using a different time zone setting, or a different computer entirely.

    This is a good reason to format any USB thumbdrive or SD cards you might use as exFAT instead of FAT32.

like image 101
Matt Johnson-Pint Avatar answered Nov 14 '22 18:11

Matt Johnson-Pint