Moon
Moon

Reputation: 33

Prolog Get the differences in days between two dates

I've been trying to compare 2 dates in prolog.

The dates format is date(YYYY, MM, DD)

ex: (2016,04,21).

I want to compare two dates and know if the difference (in days) between those dates is bigger than 15 days (2 weeks).

%dateDifference( number_of_day, date_no1, date_no2 ).
dateDifference( 35, date(2003,8,16), date(2003,9,20) ).

Upvotes: 1

Views: 2377

Answers (2)

Paulo Moura
Paulo Moura

Reputation: 18683

Computing the difference in days between two dates can be simple or tricky depending on the calendar and on the covered periods. Assuming the Gregorian calendar, the common solution is to convert the dates to Julian days. As @mat mentioned in its comment, for SWI-Prolog, consider the library(julian);

https://github.com/mndrix/julian

For a portable solution that can be used with most Prolog systems (including SWI-Prolog), Logtalk includes a third-party ISO 8601 library that can be used for these computations:

http://logtalk.org/library/iso8601_0.html

Upvotes: 2

Ans Piter
Ans Piter

Reputation: 573

first off, you should put account the note of @Boris, second, in order to simplify the issue, your predicate divided into three parts:

part 1:

  • know if year is leap or common,
  • affect the number of days for each month,
  • Finally this part follow the following rule;

code :

calcule_days([Y,M,D],Res):-
    Res is (((Y*1461)/4)+((M*153)/5)+D).

part 2 :

  • calculates the difference between the two dates so
  • apply the formula (part1) with date1 and date2,
  • calculate the differences between the two results difference_date1_date2 ,
  • to avoid the negative sign add abs(difference_date1_date2)
  • to obtain a value added approach round (result_abs_pred)

demo code :

dateDifference(NumberOfDays,date(YEAR1,MONTH1,DAY1),date(YEAR2,MONTH2,DAY2)):-
           ...

part3:

  • testing whether the result is >= 15, result must be True/false

demo code :

bigger_2weeks(date(YEAR1,MONTH1,DAY1),date(YEAR2,MONTH2,DAY2)):-
...

Upvotes: 0

Related Questions