[JAVA-6221] Fix TimeApi unit test

This commit is contained in:
Haroon Khan 2021-08-13 18:39:14 +01:00
parent 179b9ef2fd
commit f9dc97d25e
2 changed files with 21 additions and 13 deletions

View File

@ -13,12 +13,9 @@ import java.util.stream.IntStream;
public class TimeApi { public class TimeApi {
public static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate) { public static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate) {
List<Date> datesInRange = new ArrayList<Date>(); List<Date> datesInRange = new ArrayList<>();
Calendar calendar = new GregorianCalendar(); Calendar calendar = getCalendarWithoutTime(startDate);
calendar.setTime(startDate); Calendar endCalendar = getCalendarWithoutTime(endDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
while (calendar.before(endCalendar)) { while (calendar.before(endCalendar)) {
Date result = calendar.getTime(); Date result = calendar.getTime();
@ -40,4 +37,15 @@ public class TimeApi {
return startDate.datesUntil(endDate).collect(Collectors.toList()); return startDate.datesUntil(endDate).collect(Collectors.toList());
} }
private static Calendar getCalendarWithoutTime(Date date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
} }

View File

@ -18,19 +18,19 @@ public class TimeApiUnitTest {
Date endDate = endCalendar.getTime(); Date endDate = endCalendar.getTime();
List<Date> dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate); List<Date> dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate);
assertEquals(dates.size(), 2); assertEquals(2, dates.size());
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
Date date1 = calendar.getTime(); Date date1 = calendar.getTime();
assertEquals(dates.get(0).getDay(), date1.getDay()); assertEquals(date1.getDay(), dates.get(0).getDay());
assertEquals(dates.get(0).getMonth(), date1.getMonth()); assertEquals(date1.getMonth(), dates.get(0).getMonth());
assertEquals(dates.get(0).getYear(), date1.getYear()); assertEquals(date1.getYear(), dates.get(0).getYear());
calendar.add(Calendar.DATE, 1); calendar.add(Calendar.DATE, 1);
Date date2 = calendar.getTime(); Date date2 = calendar.getTime();
assertEquals(dates.get(1).getDay(), date2.getDay()); assertEquals(date2.getDay(), dates.get(1).getDay());
assertEquals(dates.get(1).getMonth(), date2.getMonth()); assertEquals(date2.getMonth(), dates.get(1).getMonth());
assertEquals(dates.get(1).getYear(), date2.getYear()); assertEquals(date2.getYear(), dates.get(1).getYear());
} }
@Test @Test