Delphi 2010 - Seattle - TFile.GetLastWriteTimeUtc returns wrong (-1 hour), for a file timestamp set with TFile.SetLastWriteTimeUtc. Looks like caused by daylight savings offset.

Delphi 2010 - Seattle - TFile.GetLastWriteTimeUtc returns wrong (-1 hour), for a file timestamp set with TFile.SetLastWriteTimeUtc. Looks like caused by daylight savings offset.
Sample below:
var
  fileName: String;
  fileTimeStamp: TDateTime;
begin
  fileName := 'D:\testdate.txt';

  //create the file
  if not TFile.Exists(fileName) then
    TFile.WriteAllText(fileName, ' ');

  fileTimeStamp := EncodeDateTime(2015, 8, 22, 14, 26, 22, 0);

  ShowMessage('Set ' + DateTimeToStr(fileTimeStamp)); //shows 2015-08-22 14:26:22, correct

  TFile.SetLastWriteTimeUtc(fileName, fileTimeStamp);

  ShowMessage('Get ' + DateTimeToStr(TFile.GetLastWriteTimeUtc(fileName))); //shows 2015-08-22 13:26:22, wrong -1 hour
end;

Comments

  1. Interesting is that FindFirst returns the correct timestamp:

    function GetFileDateUTC(FileName: String): TDateTime;
    var
      LSearchRec: TSearchRec;
      LSystemTime: TSystemTime;
    begin
      if FindFirst(FileName, faAnyFile, LSearchRec) = 0 then begin   FileTimeToSystemTime(LSearchRec.FindData.ftLastWriteTime, LSystemTime);
        with LSystemTime do Result := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
      end;
      FindClose(LSearchRec);
    end;

    ...
      ShowMessage('Get ' + DateTimeToStr(GetFileDateUTC(fileName))); //shows 2015-08-22 14:26:22, correct

    ReplyDelete
  2. Seems that the Set method uses LocalFileTimeToFileTime while the Get method uses TTimeZone.Local.ToUniversalTime. This looks somewhat inconsistent to me.

    ReplyDelete
  3. to remember: "never use UTC for local files"

    ReplyDelete

Post a Comment