Flinkman
Flinkman

Reputation: 17745

How can I find the time difference in seconds between two dates in prolog?

How can I find the time difference in seconds between two dates in prolog?

datetime(2001,03,04,23,00,32).

datetime(2001,03,04,23,01,33).

timediff(D1,D2,Sec).

Sec=61

Upvotes: 0

Views: 2070

Answers (2)

Kaarel
Kaarel

Reputation: 10672

SWI-Prolog offers several predicates that convert human-readable time representations into seconds from Epoch (at 1970-01-01). Having the time represented as a number of seconds turns the difference calculation into a simple subtraction operation. For example:

timediff(DateTime1, DateTime2, Sec) :-
        date_time_stamp(DateTime1, TimeStamp1),
        date_time_stamp(DateTime2, TimeStamp2),
        Sec is TimeStamp2 - TimeStamp1.

Usage:

?- timediff(date(2001, 03, 04, 23, 0, 32, 0, -, -),
            date(2001, 03, 04, 23, 1, 33, 0, -, -), Sec).
Sec = 61.0.

Upvotes: 1

Raceimaztion
Raceimaztion

Reputation: 9644

This gets a little awkward what with the months not being the same length and leap years having extra days.

To start you off, I'm going to give you a version of a predicate that will only take into account hours, minutes, and seconds:

timediff(time(Hours1, Minutes1, Seconds1), time(Hours2, Minutes2, Seconds2), Seconds) :-
    Seconds is Seconds1-Seconds2 + 60*(Minutes1-Minutes2 + 60*(Hours1-Hours2)).

If you could run convert_time/2 or convert_time/8 backwards, this process would be much easier, as it would allow you to use the operating system's time conversion routines instead of writing your own.

Upvotes: 0

Related Questions