How to get current system year as a number in prolog. I found this. But it gives the year as a string.
today(Today) :- get_time(X), format_time(atom(Today), '%Y', X).
Thanks.
As mbratch notes in the comments to my answer, format_time/3
is for displaying date and time values. If I just needed the data, I wouldn't use format_time/3
, but rather stamp_date_time/3
and date_time_value/3
to convert the time stamp into the values you need. Documentation on the relevant predicates can be found here.
To get the current year, a predicate like this will suffice:
year(Year) :-
get_time(Stamp),
stamp_date_time(Stamp, DateTime, local),
date_time_value(year, DateTime, Year).
Here is a descriptions of the built-in predicates used:
get_time/2
gives a float representing the elapsed time since the Unix Epoch. stamp_date_time/3
converts the stamp to a term date/9
, according to the time-zone indicated by the third argument. When the time-zone argument is local
it gets the time-zone which your system takes to be local. An example of date/9
:
date(2014, 3, 29, 8, 8, 59.30211305618286, 21600, 'MDT', true)
date_time_value/3
: lets you extract values from a date/9
term (so you don't have to do silly things like date(Year,_,_,_,_,_,_,_,_)
to get a simple value).
Your question asks for the year, but your example predicate looks like it describes today's date, which would look like this:
today(Today) :-
get_time(Stamp),
stamp_date_time(Stamp, DateTime, local),
date_time_value(date, DateTime, Today).
The with the date
keyword, date_time_value/3
will instantiate Today
to a term date/3
, holding the year, month, and day: e.g., date(2014, 3, 29)
.
Really, it's a bit silly that the library requires three statements to get a common date-time value, so if you're handling time and dates often, you might just want to use a general purpose predicate like
get_date_time_value(Key, Value) :-
get_time(Stamp),
stamp_date_time(Stamp, DateTime, local),
date_time_value(Key, DateTime, Value).
Which will return the current numerical value corresponding to the given Key
:
?- get_date_time_value(day, X).
X = 29.
?- get_date_time_value(year, X).
X = 2014.
?- get_date_time_value(date, X).
X = date(2014, 3, 29).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With