Epoch in Pascal

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Pascal.

program Epoch;

uses
  SysUtils, DateUtils;

var
  Now: TDateTime;
  UnixTime: Int64;
  UnixTimeMilliseconds: Int64;
  UnixTimeNanoseconds: Int64;

begin
  // Get the current date and time
  Now := SysUtils.Now;
  Writeln(DateTimeToStr(Now));

  // Convert to Unix timestamp (seconds since epoch)
  UnixTime := DateTimeToUnix(Now);
  Writeln(UnixTime);

  // Convert to milliseconds
  UnixTimeMilliseconds := DateTimeToUnix(Now) * 1000 + MilliSecondOf(Now);
  Writeln(UnixTimeMilliseconds);

  // Convert to nanoseconds (Note: Pascal doesn't have nanosecond precision)
  UnixTimeNanoseconds := UnixTimeMilliseconds * 1000000;
  Writeln(UnixTimeNanoseconds);

  // Convert Unix timestamp back to TDateTime
  Writeln(DateTimeToStr(UnixToDateTime(UnixTime)));

  // Convert Unix timestamp with milliseconds back to TDateTime
  Writeln(DateTimeToStr(UnixToDateTime(UnixTime) + EncodeTime(0, 0, 0, MilliSecondOf(Now))));
end.

In this Pascal program, we use the SysUtils and DateUtils units to work with date and time functions.

We use SysUtils.Now to get the current date and time.

To get the Unix timestamp (seconds since epoch), we use the DateTimeToUnix function.

For milliseconds, we multiply the Unix timestamp by 1000 and add the milliseconds of the current time.

Pascal doesn’t have built-in nanosecond precision, so we approximate it by multiplying the milliseconds by 1,000,000.

We can also convert Unix timestamps back to TDateTime using the UnixToDateTime function.

Here’s an example of what the output might look like:

2023-06-01 15:30:45
1685633445
1685633445745
1685633445745000000
2023-06-01 15:30:45
2023-06-01 15:30:45.745

Note that the exact values will depend on when you run the program.

Next, we’ll look at another time-related task: time parsing and formatting.