Eric Hubbard
Eric Hubbard

Reputation: 41

How do you compare times in Java?

I'm wondering how I would compare times in a Java program. For example: If I choose a time block from 09:00-12:00 and set that. If i choose a second time and choose 11:00-13:00 time period, I would want to be able to have an error pop up, but I'm not exactly sure how to set that up.

For example if you are reserving a time at a massage therapy place from 9-12, you can't reserve another one for yourself at 11-1, it wouldn’t make sense. I'm trying to figure out how to put it into code. My noob level is having me think to have a string as a selection method, then parse the string to integer and compare the integer for overlapping? I want to use the Date class though because it seems very useful and I'd like to learn how to use it.

Upvotes: 0

Views: 200

Answers (1)

Anonymous
Anonymous

Reputation: 86282

LocalTime from java.time

    LocalTime blockStart = LocalTime.of(9, 0);
    LocalTime blockEnd = LocalTime.of(12, 0);
    assert blockEnd.isAfter(blockStart);

    LocalTime newBlockStart = LocalTime.of(11, 0);
    LocalTime newBlockEnd = LocalTime.of(13, 0);
    assert newBlockEnd.isAfter(newBlockStart);

    if (newBlockStart.isBefore(blockEnd) && newBlockEnd.isAfter(blockStart)) {
        System.out.println("" + newBlockStart + '–' + newBlockEnd
                + " overlaps with " + blockStart + '–' + blockEnd);
    }

Output from the snippet is:

11:00–13:00 overlaps with 09:00–12:00

A LocalTime is a time of day without a date. A potential liability is that it cannot take into account if the clock is turned forward or backward, for example when summer time (DST) begins or ends. But if you want nothing that fancy, it’s the correct class to use.

The formula for detecting an overlap is standard. I include a link to a question about it below.

I want to use the Date class though…

Don’t, don’t, please don’t. The Date is poorly designed and long outdated. You are seriously better off not learning how to use that class. Learn to use java.time, the modern Java date and time API. A possible place to start is the first link below.

Links

Upvotes: 1

Related Questions