Search code examples
delphidelphi-xe2

How can I automate getting the date of build into a constant visible to my code?


I would like to define in my code a constant holding the date on which the executable was built. I would naturally like to automate that process.

I know that I can write a pre-build script using, for example, Perl, to write out a .inc file containing the date. I would prefer a more lightweight solution using, perhaps, environment variables or build variables. Does msbuild provide any variables that would help? Does anyone know a neater solution to the problem?


Solution

  • You can read the linker timestamp from the PE header of the executable:

    uses
      ImageHlp;
    
    function LinkerTimeStamp(const FileName: string): TDateTime; overload;
    var
      LI: TLoadedImage;
    begin
      Win32Check(MapAndLoad(PChar(FileName), nil, @LI, False, True));
      Result := LI.FileHeader.FileHeader.TimeDateStamp / SecsPerDay + UnixDateDelta;
      UnMapAndLoad(@LI);
    end;
    

    For the loaded image of the current module, the following seems to work:

    function LinkerTimestamp: TDateTime; overload;
    begin
      Result := PImageNtHeaders(HInstance + Cardinal(PImageDosHeader(HInstance)^._lfanew))^.FileHeader.TimeDateStamp / SecsPerDay + UnixDateDelta;
    end;
    

    Earlier versions of Delphi didn't update it correctly but it has been fixed around Delphi 2010 or so. For the earlier versions, I used an IDE plugin to update it automatically after a successful compile.

    Note: The value is stored as UTC so for display purposes you may need to convert it to an appropriate timezone.