Time Formatting Parsing in Chapel

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

use Time;
use IO;

proc main() {
  var p = writeln;

  // Here's a basic example of formatting a time
  // according to ISO8601, which is similar to RFC3339
  var t = getCurrentTime();
  p(t.isoFormat());

  // Time parsing uses a similar approach
  var t1 = ISO8601_FORMAT.parse("2012-11-01T22:08:41+00:00");
  p(t1);

  // Chapel uses format strings for time formatting.
  // These are different from the example-based layouts in the original code,
  // but serve a similar purpose.
  p(t.format("%I:%M %p"));
  p(t.format("%a %b %d %H:%M:%S %Y"));
  p(t.format("%Y-%m-%dT%H:%M:%S.%f%z"));

  var form = "%I %M %p";
  var t2 = form.parse("8 41 PM");
  p(t2);

  // For purely numeric representations you can also
  // use standard string formatting with the extracted
  // components of the time value.
  writef("%04i-%02i-%02iT%02i:%02i:%02i-00:00\n",
         t.year, t.month:int, t.day, t.hour, t.minute, t.second);

  // Parse will throw an error on malformed input
  // explaining the parsing problem.
  try {
    var _ = "%a %b %d %H:%M:%S %Y".parse("8:41PM");
  } catch e {
    p(e);
  }
}

When you run this program, you’ll see output similar to the following:

2023-05-15T10:30:15-07:00
2012-11-01T22:08:41.000000
10:30 AM
Mon May 15 10:30:15 2023
2023-05-15T10:30:15.123456-07:00
0000-01-01T20:41:00.000000
2023-05-15T10:30:15-00:00
Error: Parsing failed

Note that Chapel’s time handling is somewhat different from the original example. Chapel uses the Time module for time-related operations, and its formatting and parsing methods are slightly different. The ISO8601_FORMAT is used as an equivalent to RFC3339, and format strings are used instead of example-based layouts.

Chapel’s error handling is also different, using try-catch blocks instead of returning error values.

Remember that the exact output will depend on when and where you run the program, as it uses the current time in some of the examples.