baeldung-articles : BAEL-6596 (#16143)

Check if a given time lies between two times regardless of date.
This commit is contained in:
DiegoMarti2 2024-03-18 20:40:01 +02:00 committed by GitHub
parent faf223b47a
commit bb3e43fdec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,45 @@
package com.baeldung.checkiftimebetweentwotimes;
import org.junit.Test;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.assertTrue;
public class CheckIfTimeBetweenTwoTimesUnitTest {
private LocalTime startTime = LocalTime.parse("09:00:00");
private LocalTime endTime = LocalTime.parse("17:00:00");
private LocalTime targetTime = LocalTime.parse("12:30:00");
@Test
public void givenLocalTime_whenUsingIsAfterIsBefore_thenTimeIsBetween() {
assertTrue(!targetTime.isBefore(startTime) && !targetTime.isAfter(endTime));
}
@Test
public void givenLocalTime_whenUsingCompareTo_thenTimeIsBetween() {
assertTrue(targetTime.compareTo(startTime) >= 0 && targetTime.compareTo(endTime) <= 0);
}
@Test
public void givenDate_whenUsingAfterBefore_thenTimeIsBetween() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(Calendar.HOUR_OF_DAY, 9);
startCalendar.set(Calendar.MINUTE, 0);
Date startTime = startCalendar.getTime();
Calendar endCalendar = Calendar.getInstance();
endCalendar.set(Calendar.HOUR_OF_DAY, 17);
endCalendar.set(Calendar.MINUTE, 0);
Date endTime = endCalendar.getTime();
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(Calendar.HOUR_OF_DAY, 12);
targetCalendar.set(Calendar.MINUTE, 30);
Date targetTime = targetCalendar.getTime();
assertTrue(!targetTime.before(startTime) && !targetTime.after(endTime));
}
}