开发者

How to Compare Dates and Times?

How can I compare whether two datetimes are the same or at least overlap?

For example, let's say we have the following t开发者_Go百科wo sets of start and stop times:

Start time: 2011-07-21 9:00am Stop time: 2011-07-21 10:00am

Start time: 2011-07-21 9:05am Stop time: 2011-07-21 10:30am

The datetimes do not match exactly, so I can't do a straight equality test. However, for my purposes the datetimes overlap is sufficient to be deemed a match, how can I test for this type of overlap?


I highly recommend to use JodaTime and its overlap method.

From javadoc, it will not only tell you if it two intervals overlap. But it tells you what the overlapping interval is.

Returns: the overlap interval, null if no overlap


Use JODA or write a DateRange class of your own to encapsulate the logic.


I am guessing you need a algo to do it and not java syntax.

You could subtract the Second start time from First stop time, and put a threshold on the difference depending on what is an acceptable overlap.


If you want to do it in pure Java, use a Calendar object and compareTo() == 0

For overlap, set seconds, minutes, etc. to 0 until you get the desired "precision".

Alternatively (for more fine grained precision), convert both to long and use Math.abs( t1 - t2 ) to get the difference in milliseconds.


Have a look at the following example code (hope you do not mind deprecated APIs as this is just an example).

public class DateOverlapTest {

    public static void main(final String... args) {

        Date start1 = new Date(2011, 6, 21, 9, 0);
        Date stop1 = new Date(2011, 6, 21, 10, 0);

        Date start2 = new Date(2011, 6, 21, 9, 5);
        Date stop2 = new Date(2011, 6, 21, 10, 30);

        System.out.println("Start1: " + start1);
        System.out.println("Stop1 : " + stop1);
        System.out.println("Start2: " + start2);
        System.out.println("Stop2 : " + stop2);

        // start2 has to be before or equal stop1 and
        // stop2 has to be after or equal start1
        boolean overlap = start2.compareTo(stop1) <= 0
                && stop2.compareTo(start1) >= 0;

        System.out.println("Overlaps: " + overlap);

    }

}

output is:

Start1: Fri Jul 21 09:00:00 CEST 3911
Stop1 : Fri Jul 21 10:00:00 CEST 3911
Start2: Fri Jul 21 09:05:00 CEST 3911
Stop2 : Fri Jul 21 10:30:00 CEST 3911
Overlaps: true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜