Time in Prolog

Prolog offers support for handling dates and times through various libraries. Here’s an example using the library(time) module:

:- use_module(library(time)).

main :-
    % We'll start by getting the current time.
    get_time(Now),
    format_time(atom(NowStr), '%Y-%m-%d %H:%M:%S', Now),
    writeln(NowStr),

    % You can create a timestamp by providing the date and time components.
    date_time_stamp(date(2009, 11, 17, 20, 34, 58.651387237), Then),
    format_time(atom(ThenStr), '%Y-%m-%d %H:%M:%S', Then),
    writeln(ThenStr),

    % You can extract the various components of the time value as expected.
    stamp_date_time(Then, DateTime, 'UTC'),
    date_time_value(year, DateTime, Year),
    date_time_value(month, DateTime, Month),
    date_time_value(day, DateTime, Day),
    date_time_value(hour, DateTime, Hour),
    date_time_value(minute, DateTime, Minute),
    date_time_value(second, DateTime, Second),
    writeln(Year), writeln(Month), writeln(Day),
    writeln(Hour), writeln(Minute), writeln(Second),

    % The day of the week is also available.
    day_of_the_week(date(2009, 11, 17), DayOfWeek),
    writeln(DayOfWeek),

    % These predicates compare two times, testing if the first occurs before,
    % after, or at the same time as the second, respectively.
    (Then @< Now -> writeln(true) ; writeln(false)),
    (Then @> Now -> writeln(true) ; writeln(false)),
    (Then =:= Now -> writeln(true) ; writeln(false)),

    % We can compute the difference between two timestamps.
    Diff is Now - Then,
    format('~3f~n', [Diff]),

    % We can compute the length of the duration in various units.
    Hours is Diff / 3600,
    Minutes is Diff / 60,
    Seconds is Diff,
    format('~3f~n', [Hours]),
    format('~3f~n', [Minutes]),
    format('~3f~n', [Seconds]),

    % You can use arithmetic to advance a time by a given duration,
    % or subtract to move backwards.
    Advanced is Then + Diff,
    format_time(atom(AdvancedStr), '%Y-%m-%d %H:%M:%S', Advanced),
    writeln(AdvancedStr),
    
    Backward is Then - Diff,
    format_time(atom(BackwardStr), '%Y-%m-%d %H:%M:%S', Backward),
    writeln(BackwardStr).

To run this program, save it to a file (e.g., time_example.pl) and use the Prolog interpreter:

$ swipl -s time_example.pl -g main -t halt

This will produce output similar to the following:

2023-05-31 10:15:30
2009-11-17 20:34:58
2009
11
17
20
34
58
2
true
false
false
425908532.348613
118307.925652
7098475.539143
425908532.348613
2023-05-31 10:15:30
1996-05-06 06:54:26

Note that Prolog’s date and time handling might differ slightly from other languages. The library(time) module provides predicates for working with timestamps, but some operations (like extracting specific components or performing arithmetic) may require additional steps or conversions.

Next, we’ll explore other aspects of Prolog programming.