Time in Pascal

Pascal offers support for times and durations; here are some examples.

program TimeExample;

uses
  SysUtils, DateUtils;

var
  now, then: TDateTime;
  diff: TDateTime;

procedure PrintDateTime(dt: TDateTime);
begin
  WriteLn(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', dt));
end;

begin
  // We'll start by getting the current time.
  now := Now;
  PrintDateTime(now);

  // You can build a TDateTime by providing the year, month, day, etc.
  then := EncodeDateTime(2009, 11, 17, 20, 34, 58, 651);
  PrintDateTime(then);

  // You can extract the various components of the time value as expected.
  WriteLn(YearOf(then));
  WriteLn(MonthOf(then));
  WriteLn(DayOf(then));
  WriteLn(HourOf(then));
  WriteLn(MinuteOf(then));
  WriteLn(SecondOf(then));
  WriteLn(MilliSecondOf(then));

  // The day of the week is also available.
  WriteLn(DayOfTheWeek(then));

  // These comparisons test if the first occurs before, after, or at the same time as the second.
  WriteLn(CompareDateTime(then, now) < 0);
  WriteLn(CompareDateTime(then, now) > 0);
  WriteLn(CompareDateTime(then, now) = 0);

  // We can compute the interval between two times.
  diff := now - then;
  WriteLn(FormatDateTime('hh:nn:ss.zzz', diff));

  // We can compute the length of the duration in various units.
  WriteLn(HoursBetween(now, then):0:2);
  WriteLn(MinutesBetween(now, then):0:2);
  WriteLn(SecondsBetween(now, then):0:2);
  WriteLn(MilliSecondsBetween(now, then):0:2);

  // You can use IncHour, IncMinute, etc. to advance a time by a given duration.
  WriteLn(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', IncHour(then, 1)));
  WriteLn(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', IncHour(then, -1)));
end.

To run the program, save it as TimeExample.pas and use a Pascal compiler like Free Pascal:

$ fpc TimeExample.pas
$ ./TimeExample

This will output the current time, the specified time, and various time-related calculations and comparisons.

Note that Pascal’s datetime handling is somewhat different from Go’s. Pascal uses TDateTime for both date/time values and durations, while Go has separate time.Time and time.Duration types. The Pascal code attempts to provide similar functionality using the available tools in the language.

Also, Pascal doesn’t have a built-in UTC time zone concept like Go does. If you need to work with UTC times in Pascal, you would typically need to use a third-party library or implement the conversions yourself.

Next, we’ll look at the related idea of time relative to the Unix epoch.