Time in Ada

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

with Ada.Text_IO;
with Ada.Calendar;
with Ada.Calendar.Formatting;
with Ada.Calendar.Time_Zones;

procedure Time_Example is
   use Ada.Text_IO;
   use Ada.Calendar;
   use Ada.Calendar.Formatting;
   use Ada.Calendar.Time_Zones;

   procedure P (Item : String) is
   begin
      Put_Line (Item);
   end P;

   Now  : Time := Clock;
   Then : Time := Time_Of (2009, 11, 17, 20, 34, 58);
   Diff : Duration;
begin
   -- We'll start by getting the current time.
   P (Image (Now));

   -- You can build a Time value by providing the year, month, day, etc.
   -- Times are always associated with a time zone.
   P (Image (Then));

   -- You can extract the various components of the time value as expected.
   P (Year (Then)'Image);
   P (Month (Then)'Image);
   P (Day (Then)'Image);
   P (Hour (Then)'Image);
   P (Minute (Then)'Image);
   P (Second (Then)'Image);

   -- The day of the week is also available.
   P (Day_Name (Then)'Image);

   -- These functions compare two times, testing if the first occurs before,
   -- after, or at the same time as the second, respectively.
   P (Boolean'Image (Then < Now));
   P (Boolean'Image (Then > Now));
   P (Boolean'Image (Then = Now));

   -- We can compute the duration between two times.
   Diff := Now - Then;
   P (Duration'Image (Diff));

   -- We can compute the length of the duration in various units.
   P (Duration'Image (Diff / 3600.0)); -- Hours
   P (Duration'Image (Diff / 60.0));   -- Minutes
   P (Duration'Image (Diff));          -- Seconds

   -- You can use "+" to advance a time by a given duration,
   -- or with a "-" to move backwards by a duration.
   P (Image (Then + Diff));
   P (Image (Then - Diff));
end Time_Example;

To run the program, save it as time_example.adb and use the Ada compiler (e.g., GNAT):

$ gnatmake time_example.adb
$ ./time_example

This will output the current time, the specified time (2009-11-17 20:34:58), and various time calculations and comparisons.

Note that Ada’s standard library provides robust time handling capabilities, but the exact output format might differ from what’s shown in the original example. The Ada.Calendar and Ada.Calendar.Formatting packages offer extensive functionality for working with dates and times.

Ada doesn’t have a direct equivalent to Go’s nanosecond precision or Location type, but it does provide time zone support through Ada.Calendar.Time_Zones. The examples here use UTC implicitly.

Remember that Ada is strongly typed, so some conversions between types (like Time to String) require explicit Image or formatting functions.

Next, we’ll look at the related idea of time relative to the Unix epoch, although Ada doesn’t have a built-in concept of “Unix time” in its standard library.