Как проверить, находится ли Date в определенном диапазоне в Java?
Пример Java, чтобы проверить, находится ли предоставленная дата в диапазоне 3 месяцев до и после текущей даты. Идея довольно проста, просто используйте классCalendar для отката месяца назад и вперед, чтобы создать «диапазон дат», и используйтеDate.before()
иDate.after()
, чтобы проверить, находится ли дата в пределах диапазон.
if (dateToValidate.before(currentDateAfter3Months.getTime()) && dateToValidate.after(currentDateBefore3Months.getTime())) {
Смотрите полный пример.
package com.example.date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateValidator { public boolean isThisDateWithin3MonthsRange(String dateToValidate, String dateFromat) { SimpleDateFormat sdf = new SimpleDateFormat(dateFromat); sdf.setLenient(false); try { // if not valid, it will throw ParseException Date date = sdf.parse(dateToValidate); // current date after 3 months Calendar currentDateAfter3Months = Calendar.getInstance(); currentDateAfter3Months.add(Calendar.MONTH, 3); // current date before 3 months Calendar currentDateBefore3Months = Calendar.getInstance(); currentDateBefore3Months.add(Calendar.MONTH, -3); /*************** verbose ***********************/ System.out.println("\n\ncurrentDate : " + Calendar.getInstance().getTime()); System.out.println("currentDateAfter3Months : " + currentDateAfter3Months.getTime()); System.out.println("currentDateBefore3Months : " + currentDateBefore3Months.getTime()); System.out.println("dateToValidate : " + dateToValidate); /************************************************/ if (date.before(currentDateAfter3Months.getTime()) && date.after(currentDateBefore3Months.getTime())) { //ok everything is fine, date in range return true; } else { return false; } } catch (ParseException e) { e.printStackTrace(); return false; } } }
Простой модульный тест для проверки приведенного выше кода работает правильно, если вы запустите ниже модульный тест, все случаи будут пройдены.
package com.example.test; import org.junit.*; import com.example.date.DateValidator; import static org.junit.Assert.*; public class DateValidatorRangeTest { private DateValidator dateValidator; @Before public void init() { dateValidator = new DateValidator(); } @Test public void testDateWithinRange_1() { assertTrue(dateValidator.isThisDateWithin3MonthsRange("31/01/2012", "dd/MM/yyyy")); } @Test public void testDateWithinRange_2() { assertFalse(dateValidator.isThisDateWithin3MonthsRange("31/01/2011", "dd/MM/yyyy")); } @Test public void testDateWithinRange_3() { assertTrue(dateValidator.isThisDateWithin3MonthsRange("20/02/2012", "dd/MM/yyyy")); } @Test public void testDateWithinRange_4() { assertFalse(dateValidator.isThisDateWithin3MonthsRange("21/05/2012", "dd/MM/yyyy")); } }
Все случаи передаются и выводятся после дополнительной информации на консоли.
currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 31/01/2012 currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 31/01/2011 currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 20/02/2012 currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 21/05/2012