Time in Chapel

Our first program will demonstrate working with time in Chapel. Here’s the full source code:

use Time;
use IO;

proc main() {
  // We'll start by getting the current time.
  var now = getCurrentTime();
  writeln(now);

  // You can build a time struct by providing the
  // year, month, day, etc. Times are always associated
  // with a time zone.
  var then = createDateTime(2009, 11, 17, 20, 34, 58, 651387237, "UTC");
  writeln(then);

  // You can extract the various components of the time
  // value as expected.
  writeln(then.year);
  writeln(then.month);
  writeln(then.day);
  writeln(then.hour);
  writeln(then.minute);
  writeln(then.second);
  writeln(then.microsecond);
  writeln(then.timezone);

  // The day of the week is also available.
  writeln(then.weekday());

  // These methods compare two times, testing if the
  // first occurs before, after, or at the same time
  // as the second, respectively.
  writeln(then < now);
  writeln(then > now);
  writeln(then == now);

  // We can compute the difference between two times.
  var diff = now - then;
  writeln(diff);

  // We can compute the length of the duration in
  // various units.
  writeln(diff.hours());
  writeln(diff.minutes());
  writeln(diff.seconds());
  writeln(diff.microseconds());

  // You can use addition to advance a time by a given
  // duration, or subtraction to move backwards by a
  // duration.
  writeln(then + diff);
  writeln(then - diff);
}

To run the program, save the code in a file with a .chpl extension and use the chpl compiler:

$ chpl time.chpl -o time
$ ./time

This will output the current time, a specific time in 2009, and various time-related calculations.

Chapel’s Time module provides functionality for working with dates, times, and durations. The getCurrentTime() function returns the current time, while createDateTime() allows you to create a specific time.

Methods like year, month, day, etc., allow you to extract components of a time. The <, >, and == operators can be used to compare times.

The - operator between two times gives a duration, which can be queried for various units like hours, minutes, seconds, and microseconds.

Finally, you can add or subtract durations from times to get new times.

Note that Chapel’s time handling might differ slightly from other languages, but it provides similar functionality for working with dates and times.