我有一个 DateTime
需要转换为 NodaTime LocalDate
。这能做到吗?
我有这个:
DateTime modifiedDate = File.GetLastWriteTime(file);
我想要这个:
LocalTime modifiedDate = File.GetLastWriteTime(file);
但看起来 NodaTime
API 无法从 GetLastWriteTime
获取日期值。
所以我要么需要
a) 将 DateTime 转换为 LocalTime 或
b) 以某种方式使用 LocalTime 从 GetLastWriteTime
最佳答案
Noda Time 的主要设计决策之一是,计算机的本地时区设置不应产生副作用。在内部,GetLastWriteTime
调用 GetLastWriteTimeUtc().ToLocalTime()
。因此,只要调用 GetLastWriteTime
,您就违反了这一理想。
读取文件时间的正确 Noda Time 类型是 Instant
。
Instant instant = Instant.FromDateTimeUtc(File.GetLastWriteTimeUtc(file));
从那里,如果您需要本地日期和/或时间,则可以应用时区。
首先,确定您想要的时区。例如:
DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/New_York"];
如果出于某种原因想要使用计算机自己的本地时区,请使用:
DateTimeZone zone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
然后将时区应用于您的文件时间:
ZonedDateTime zonedDateTime = instant.InZone(zone);
然后您可以从其中任何一个中进行选择,具体取决于您要查找的内容:
LocalDateTime localDateTime = zonedDateTime.LocalDateTime;
LocalDate date = zonedDateTime.Date;
LocalTime time = zonedDateTime.TimeOfDay;
此外,您应该了解在磁盘上,文件时间取决于您使用的文件系统类型。
如果您使用的是 NTFS,则磁盘上的时间以 UTC 记录。这是非常需要的。
如果您使用的是 exFAT,磁盘上的时间将以本地日期 + 时间记录,但它还包括与 UTC 的偏移量,因此可以轻松地将其转换回 UTC 而不会产生歧义。
如果您使用的是 FAT 或 FAT32 文件系统,磁盘上的时间将使用本地时间记录,按写入文件时有效的时区。 p>
这会产生不明确的数据,因为您可能在 daylight saving time 期间写入文件回退过渡,或者您可能正在使用不同的时区设置或完全不同的计算机读取数据。
这是将您可能使用的任何 USB 拇指驱动器或 SD 卡格式化为 exFAT 而不是 FAT32 的充分理由。
关于c# - DateTime 到 LocalDate (NodaTime),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23119358/