【问题标题】:How to get File Created, Accessed and Modified dates the same as windows properties?如何使文件的创建、访问和修改日期与 Windows 属性相同?
【发布时间】:2012-03-01 20:05:17
【问题描述】:

我正在尝试获取与 windows 属性中显示的相同的创建、访问和修改日期,如下所示:

但我发现时间始终是 30 分钟:

相信这可能与时区/夏令时有关,但一直无法找到解决方案。试过看: 时区偏差以及调整和查看不同的方法,包括: How to get create/last modified dates of a file in Delphi?

当前代码:

var
MyFd TWin32FindData;
FName: string;
MyTime: TFileTime;
MySysTime: TSystemTime;
myDate, CreateTime, AccessTime, ModTime: TDateTime; 
Begin
 ...
 FindFirstFile(PChar(FName), MyFd);
 MyTime:=MyFd.ftCreationTime;
 FileTimeToSystemTime(MyTime, MySysTime);
 myDate := EncodeDateTime(MySysTime.wYear, MySysTime.wMonth, MySysTime.wDay, MySysTime.wHour,
 MySysTime.wMinute, MySysTime.wSecond, MySysTime.wMilliseconds);
 Memo1.Lines.Add('Created: '+ FormatDateTime('dddd, d mmmm yyyy, hh:mm:ss ampm', MyDate));
 ...

任何帮助表示赞赏

谢谢 保罗

【问题讨论】:

  • 您没有告诉我们您目前是如何获取信息的。
  • David - 添加了当前代码,但尝试了多种方法
  • 好的,您错过了从 UTC 到本地时间的转换。我的回答以及 Kobik 的展示如何做到这一点。

标签: windows delphi winapi


【解决方案1】:

我不确定您当前的代码有什么问题,但我相信此代码会使用标准的 Windows API 调用来满足您的需求。

procedure TMyForm.ReportFileTimes(const FileName: string);

  procedure ReportTime(const Name: string; const FileTime: TFileTime);
  var
    SystemTime, LocalTime: TSystemTime;
  begin
    if not FileTimeToSystemTime(FileTime, SystemTime) then
      RaiseLastOSError;
    if not SystemTimeToTzSpecificLocalTime(nil, SystemTime, LocalTime) then
      RaiseLastOSError;
    Memo1.Lines.Add(Name + ': ' + DateTimeToStr(SystemTimeToDateTime(LocalTime)));
  end;

var
  fad: TWin32FileAttributeData;

begin
  if not GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @fad) then
    RaiseLastOSError;
  Memo1.Clear;
  Memo1.Lines.Add(FileName);
  ReportTime('Created', fad.ftCreationTime);
  ReportTime('Modified', fad.ftLastWriteTime);
  ReportTime('Accessed', fad.ftLastAccessTime);
end;

procedure TMyForm.Button1Click(Sender: TObject);
begin
  ReportFileTimes(Edit1.Text);
end;

【讨论】:

    【解决方案2】:

    您应该能够使用以下代码将 UTC 日期时间值转换为本地日期时间值:

    uses
      Windows;
    
    function UTCTimeToLocalTime(const aValue: TDateTime): TDateTime;
    var
      lBias: Integer;
      lTZI: TTimeZoneInformation;
    begin
      lBias := 0;
      case GetTimeZoneInformation(lTZI) of
        TIME_ZONE_ID_UNKNOWN:
          lBias := lTZI.Bias;
        TIME_ZONE_ID_DAYLIGHT:
          lBias := lTZI.Bias + lTZI.DaylightBias;
        TIME_ZONE_ID_STANDARD:
          lBias := lTZI.Bias + lTZI.StandardBias;
      end;
      // UTC = local time + bias
      // bias is in number of minutes, TDateTime is in days
      Result := aValue - (lBias / (24 * 60));
    end;
    

    从您的图像来看,您的偏移量实际上是 10 小时 30 分钟。你在南澳大利亚吗?

    【讨论】:

    • 亨里克,是的,南澳大利亚阿德莱德。这能够将所有时间转换为与 Windows 属性相同的时间。珍惜你的时间
    • 你抓住了他! :-) 另一种方式是FileTimeToLocalFileTime
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    相关资源
    最近更新 更多