Question

I am using a simple command to get the file date from a file, but keep getting the wrong date.

On my computer i looked and saw the date was 14/3/2014. But when i run the command i get 30/12/1999 no matter what file i try, it stays the same return date.

I've tried

BackupFileDate:=FileAge(S);;
    originalfiledate:=FileAge(fileName);

And

BackupFileDate:=GetFileModDate(S);
originalfiledate:=GetFileModDate(Filename);

function GetFileModDate(filename : string) : TDateTime;
var
   F : TSearchRec;
begin
   FindFirst(filename,faAnyFile,F);
   Result := F.TimeStamp;

   //Result := F.Time;
   FindClose(F);
end;

Both have the same result. PS: both BackupFileDate and originalfiledate are now defined as TDate, I've already tried TDateTime as-well with the same result.

I would like to get the date and time last edited of the file.

Was it helpful?

Solution

FileAge returns a time stamp used by the OS to record information such as the date and time a file was modified.

You should use the FileDateToDateTime function to convert the Integer value to a more manageable TDateTime format:

FileDateToDateTime(FileAge(fileName));

Note:

function FileAge(const FileName: string): Integer; overload;

is deprecated. There is another version of FileAge

function FileAge(const FileName: string; out FileDateTime: TDateTime; FollowLink: Boolean = True): Boolean;

that returns the time stamp of FileName in the FileDateTime output parameter.

FileAge(filename, timeDate);

EDIT

Depending on the use of the data, it may be (very) important to convert from UTC to local time.

OTHER TIPS

tl;dr Use TFile.GetLastWriteTime or TFile.GetLastWriteTimeUtc.


Your first attempt fails because FileAge returns DOS date time value. That's completely different from a TDateTime.

Your second piece of code essentially works, modulo the fact that you neglected to check for errors. The likely explanation for the error is that you passed an invalid file name. When the call to FindFirst fails, the search record that is returned is undefined.

The TimeStamp property of TSearchRec converts the file time from UTC to local, and then converts from file time to TDateTime.

You'd want to fix the lack of error handling like this:

function GetFileModDate(const FileName: string): TDateTime;
var
  F: TSearchRec;
begin
  if FindFirst(filename, faAnyFile, F)<>0 then
    raise SomeException.Create('...');
  Result := F.TimeStamp;
  FindClose(F);
end;

You should be clear that this returns a TDateTime in local time.

That said, I would do it in a platform independent way using IOUtils. Specifically TFile.GetLastWriteTime or TFile.GetLastWriteTimeUtc depending on how you want to deal with time zones.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top