Time Formatting Parsing in Pascal

Pascal supports time formatting and parsing via pattern-based layouts.

program TimeFormattingParsing;

uses
  SysUtils, DateUtils;

var
  CurrentTime: TDateTime;
  FormattedTime: string;
  ParsedTime: TDateTime;

begin
  // Here's a basic example of formatting the current time
  // according to ISO 8601 (similar to RFC3339)
  CurrentTime := Now;
  FormattedTime := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz', CurrentTime);
  WriteLn(FormattedTime);

  // Time parsing uses the same format strings as FormatDateTime
  ParsedTime := StrToDateTime('2012-11-01T22:08:41', 'yyyy-mm-dd"T"hh:nn:ss');
  WriteLn(DateTimeToStr(ParsedTime));

  // You can use various format specifiers for different date/time representations
  WriteLn(FormatDateTime('hh:nn AM/PM', CurrentTime));
  WriteLn(FormatDateTime('ddd mmm d hh:nn:ss yyyy', CurrentTime));
  WriteLn(FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz', CurrentTime));

  // Custom format parsing
  ParsedTime := StrToTime('8:41 PM', 'h:nn AM/PM');
  WriteLn(TimeToStr(ParsedTime));

  // For purely numeric representations you can also use standard string formatting
  WriteLn(Format('%d-%.2d-%.2dT%.2d:%.2d:%.2d',
    [YearOf(CurrentTime), MonthOf(CurrentTime), DayOf(CurrentTime),
     HourOf(CurrentTime), MinuteOf(CurrentTime), SecondOf(CurrentTime)]));

  // StrToDateTime will raise an exception on malformed input
  try
    ParsedTime := StrToDateTime('8:41PM', 'ddd mmm d hh:nn:ss yyyy');
  except
    on E: EConvertError do
      WriteLn(E.Message);
  end;
end.

In Pascal, we use the SysUtils and DateUtils units for date and time manipulation. The FormatDateTime function is used for formatting dates and times, while StrToDateTime and StrToTime are used for parsing.

Pascal uses format strings that are somewhat different from those in other languages. For example:

  • yyyy-mm-dd"T"hh:nn:ss.zzz is used for ISO 8601 format
  • ddd mmm d hh:nn:ss yyyy for a more readable format
  • h:nn AM/PM for time with AM/PM indicator

Note that Pascal doesn’t have a built-in constant for RFC3339 format, so we use a similar ISO 8601 format instead.

For parsing, we use the same format strings as for formatting. If the input doesn’t match the expected format, Pascal will raise an EConvertError exception.

When running this program, you might see output similar to:

2023-06-15T14:30:45.123
2012-11-01 22:08:41
02:30 PM
Thu Jun 15 14:30:45 2023
2023-06-15T14:30:45.123
20:41:00
2023-06-15T14:30:45
Error converting date/time string to TDateTime

The exact output will depend on the current date and time when you run the program.