且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IO.File.GetLastAccessTime关闭一小时

更新时间:2023-12-05 22:19:10

我可以重现此内容在XP / Win2k3 / Vista上使用.NET 4.0和2.0 / 3.5。

I can reproduce this using .NET 4.0 and 2.0/3.5 on XP/Win2k3/Vista.

问题是DST到现在都处于不同状态,.NET处理这种差异的方式有所不同到Explorer和 Scripting.FileSystemObject

The issue is DST was in a different state to now, and .NET is processing this difference differently to Explorer and Scripting.FileSystemObject.

(从zip文件中提取文件时,您会看到类似的问题, DST与压缩文件时不同。)

(You can see a similar issue when extracting files from a zip file when DST is different to when the files were zipped.)

通过Reflector,.NET与非.NET代码路径不同的原因是 IO.File (和 IO.FileInfo )实现为获取Utc日期戳并应用 .ToLocalTime ,它根据Utc时间在当地时区中是否发生了夏令时来确定要添加的偏移量。

Via Reflector, the reason .NET differs from the non .NET code paths is that all three local datestamps in IO.File (and IO.FileInfo) are implemented as getting the Utc datestamp and applying .ToLocalTime, which determines the offset to add based upon whether DST was happening in the local timezone for the Utc time.

我还检查了日期,将日期更改为去年7月1日,创建了一个文件,并查看了返回当前日期(3月16日)的时间戳(我在南澳大利亚,所以我们现在处于DST,并且不在7月1日),Windows(可能是 FileSystemObject )将DST添加到了 NOW 位置,因此显示的时间

I also checked, by changing the date to July 1 last year, creating a file and watching the timestamp when I return to the current date (March 16) (I'm in South Australia, so we're in DST now and were not on July 1), and Windows (and presumably FileSystemObject) adds the DST in place NOW so the time displayed actually changes.

因此,总而言之,.NET更正确。

So, in summary, .NET is more correct.

但是如果您想要的是错误的,但与资源管理器相同,日期使用:

But if you want the incorrect, but same as Explorer, date use:

Public Function GetLastAccessTime(ByVal FilePath As String) As Date
    Return IO.File.GetLastAccessTimeUtc(FilePath) _
      .Add(TimeZone.CurrentTimeZone.GetUtcOffset(Now))
End Function 

对此已在 Raymond Chen的博客(摘要为:.NET直观上是正确的,但并非总是可逆的,而Win32是stri完全正确且可逆)。

This has been discussed on Raymond Chen's blog (where the summary is: .NET is intuitively correct but not always invertible, and Win32 is strictly correct and invertible).