Time Formatting Parsing in Ada
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Calendar.Formatting;
with Ada.Calendar.Time_Zones;
procedure Time_Formatting_Parsing is
use Ada.Text_IO;
use Ada.Calendar;
use Ada.Calendar.Formatting;
use Ada.Calendar.Time_Zones;
Now : Time := Clock;
T1 : Time;
begin
-- Here's a basic example of formatting a time
-- according to ISO 8601, which is similar to RFC3339
Put_Line(Image(Now, Time_Zone => UTC_Time_Offset(Now)));
-- Time parsing uses a similar approach to formatting
T1 := Value("2012-11-01 22:08:41", Time_Zone => 0);
Put_Line(Image(T1));
-- Ada doesn't have example-based layouts like Go,
-- but we can create custom format strings
Put_Line(Image(Now, "%I:%M %p"));
Put_Line(Image(Now, "%a %b %d %H:%M:%S %Y"));
Put_Line(Image(Now, "%Y-%m-%dT%H:%M:%S.%i%z"));
-- For purely numeric representations you can use
-- the extracted components of the time value
Put_Line(Year(Now)'Image & "-" &
Month(Now)'Image & "-" &
Day(Now)'Image & "T" &
Hour(Now)'Image & ":" &
Minute(Now)'Image & ":" &
Second(Now)'Image & "-00:00");
-- Value will raise Time_Error on malformed input
begin
T1 := Value("8:41PM");
exception
when Time_Error =>
Put_Line("Error parsing time: invalid format");
end;
end Time_Formatting_Parsing;
This Ada program demonstrates time formatting and parsing, which is conceptually similar to the original example but uses Ada’s standard library functions.
Ada’s Calendar
and Calendar.Formatting
packages provide functionality for working with dates and times. The Image
function is used for formatting times, while the Value
function is used for parsing.
Ada doesn’t have the concept of example-based layouts like Go. Instead, it uses format strings with specific placeholders (like %Y
for year, %m
for month, etc.) to define custom formats.
Error handling in Ada is done through exceptions. The Time_Error
exception is raised when there’s an issue parsing a time string.
To run this program:
- Save the code in a file named
time_formatting_parsing.adb
- Compile it using an Ada compiler (e.g., GNAT):
$ gnatmake time_formatting_parsing.adb
- Run the compiled executable:
$ ./time_formatting_parsing
The output will be similar to the original example, showing various formatted times and demonstrating time parsing.