:- 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).