How to get the difference between two dates in seconds with Pascal

1 Answer

0 votes
program DateDifference;

{$mode objfpc}{$H+} // Enable modern Object Pascal features and long strings

uses
  SysUtils, DateUtils; // SysUtils for formatting, DateUtils for date/time arithmetic

{**
 * Calculates the total number of seconds between two TDateTime values.
 * 
 * @param AStartDateTime The starting date and time.
 * @param AEndDateTime The ending date and time.
 * @return Int64 The total number of full seconds between the two dates.
 *}
function GetSecondsBetween(AStartDateTime, AEndDateTime: TDateTime): Int64;
begin
  { DateUtils.SecondsBetween returns the absolute difference in seconds as an Int64, 
    safely handling day, hour, minute, and second boundaries. }
  Result := SecondsBetween(AStartDateTime, AEndDateTime);
end;

var
  StartDate, EndDate: TDateTime;
  TotalSeconds: Int64;
begin
  { Define start date and time using EncodeDateTime: October 27, 2026, 12:00:00.000 }
  StartDate := EncodeDateTime(2026, 10, 27, 12, 0, 0, 0);

  { Define end date and time: October 27, 2026, 12:05:30.000 }
  EndDate := EncodeDateTime(2026, 10, 27, 12, 5, 30, 0);

  { Call the function to calculate the seconds between the two dates }
  TotalSeconds := GetSecondsBetween(StartDate, EndDate);

  { Output the results to the console }
  Writeln('Start Date: ', DateTimeToStr(StartDate));
  Writeln('End Date:   ', DateTimeToStr(EndDate));
  Writeln('Total Seconds Between: ', TotalSeconds);
end.


(*
run:

Start Date: 27-10-26 12:00:00
End Date:   27-10-26 12:05:30
Total Seconds Between: 330

*)

 



answered Oct 27 by avibootz
...