Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java – How to check is a LocalTime object is before midnight

I am trying to determine if a particular LocalTime is before Midnight. Background basically I want to know if a shift’s start/end time bleed over into the next day. For example if a shift was scheduled for 23:00 – 07:00, then this would be considered bleeding into the next day since the end time is after midnight and the start time is before.

I began to implement this by seeing if the start time is before midnight, and seeing if the end time is after midnight. This would meet the criteria of being overlapping into the next day.

In Java my code looks like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public boolean checkTime() {
        
        final LocalTime startTime = LocalTime.parse("23:00");
        final LocalTime endTime = LocalTime.parse("07:00");

        return startTime.isBefore(LocalTime.MIDNIGHT) //false
                && endTime.isAfter(LocalTime.MIDNIGHT)) //true;
}

Why does it return false for the start time being not before midnight? Isn’t the time of 23:00 one hour before midnight? I would expect this to return true. Maybe I am misunderstanding something? I am working with LocalTimes and not using LocalDateTimes

>Solution :

According to the documentation, for both isBefore and isAfter:

The comparison is based on the time-line position of the time within a day.

These methods assume that the times you are comparing are on the same day, so you cannot use these to check if the period "bleeds into" the second day.

Assuming a shift must be less than 24 hours, you can check if it "bleeds into" the second day by checking if the end is before the start. This takes advantage of this "assuming the two times are in the same day" characteristic of isBefore. If isBefore thinks that endTime is before startTime, that must mean endTime is in the next day.

endTime.isBefore(startTime)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading