windowsdelphiwinapi

How to get File Created, Accessed and Modified dates the same as windows properties?


I am trying to get the same Created, Accessed and Modified dates as appears in the windows properties as in:

File Properties

But am finding the times are consistently 30 minutes out:

File Properties Delphi

Believe it may have something to do with timezones/daylight savings but have been unable to find a solution. Have tried looking at: TimeZone Bias and adjusting and looking at different methods including: How to get create/last modified dates of a file in Delphi?

Current code:

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));
 ...

Any help appreciated

Thanks Paul


Solution

  • I'm not sure what's wrong with your current code, but I believe this code will do what you need, using standard Windows API calls.

    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;