Sample code for 30+ languages & platforms
Lazarus Pascal

Compute Difference Between Two DateTime Strings

Demonstrates how to compute the difference between two datetime strings.

Chilkat Lazarus Pascal Downloads

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.CkDateTime,
  Chilkat.StringBuilder;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  t1: string;
  t2: string;
  sb1: TStringBuilder;
  count: Integer;
  sb2: TStringBuilder;
  dt1: TCkDateTime;
  dt2: TCkDateTime;
  diffSeconds: Integer;

begin
  //  Imagine we have these strings:

  t1 := '2022-11-14 15:45:38';
  t2 := '2022-11-16 17:23:41';

  //  How many minutes are between the two?

  //  First, we'd want load each date/time into a Chilkat CkDateTime object.
  //  In this case, there are no CkDateTime methods that accept the above format.
  //  However.. the CkDateTime's SetFromTimestamp will accept a date in the format "YYYY-MM-DDThh:mm:ssZ"

  //  First modify the above dates to the timestamp format.
  sb1 := TStringBuilder.Create;
  sb1.Append(t1);
  count := sb1.Replace(' ','T');
  sb1.Append('Z');

  sb2 := TStringBuilder.Create;
  sb2.Append(t2);
  count := sb2.Replace(' ','T');
  sb2.Append('Z');

  //  Load each into a CkDateTime
  dt1 := TCkDateTime.Create;
  dt1.SetFromTimestamp(sb1.GetAsString());
  //  verify...
  WriteLn(dt1.GetAsTimestamp(False));

  dt2 := TCkDateTime.Create;
  dt2.SetFromTimestamp(sb2.GetAsString());
  //  verify...
  WriteLn(dt2.GetAsTimestamp(False));

  //  Get the difference in seconds
  diffSeconds := dt2.DiffSeconds(dt1);
  WriteLn('Difference in seconds: ' + diffSeconds);
  WriteLn('Difference in minutes: ' + diffSeconds / 60);


  sb1.Free;
  sb2.Free;
  dt1.Free;
  dt2.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.