Java compare two Dates Year, month and day

I have a method for comparing two dates to see if transactionDate is in the range between validFrom and validUntil, validFrom and validUnti has a value like "2017-01-01 00:00:00", but the transaction date sometimes comes with different hours from -for switching to another time zone.

public boolean isDateWithinEmploymentDeploymentValidityPeriod(Date transcationDate, Parameter parameter) {
    return transcationDate.compareTo(parameter.getValidFrom()) >= 0
            && (parameter.getValidUntil() == null || transcationDate.compareTo(parameter.getValidUntil()) <= 0);
}

So, I need to compare the comparison only for the year Month and day and not take into account the time, what would be the most effective way without converting the date to gregorianCalendar and getting the year and month separately?

+4
source share
3 answers

LocalDate

I think a simple solution is to convert to LocalDate:

LocalDate validFrom = LocalDate.parse("2017-01-01 00:00:00", DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"));

LocalDate , , , .

validUntil . LocalDate isBefore(), isAfter(), isEqual(), compareTo().

+2

Java < 8, , (.. Calendar, , , , , ​​ Joda-Time).

, Java 8, , java.time. ( ) , java.time.LocalDate.

// Ideally, instances of the java.time classes are used throughout
// the application making this method useless.
private LocalDate toLocalDate(Date date) {
    return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).toLocalDate();
}

public boolean inRange(Date date, Date from, Date until) {
    return inRange(toLocalDate(date), toLocalDate(from), toLocalDate(until));
}

public boolean inRange(LocalDate date, LocalDate from, LocalDate until) {
    return !date.isBefore(from) && !date.isAfter(until);
}
+2

You can use the Calendar and set other parameters, except for the year, month and day, up to 0.

Calendar transactionCalendar= Calendar.getInstance();

Date transactionDate = ...;

transactionCalendar.setTime(transactionDate );
transactionCalendar.set(Calendar.HOUR_OF_DAY, 0);
transactionCalendar.set(Calendar.MINUTE, 0);
transactionCalendar.set(Calendar.SECOND, 0);
transactionCalendar.set(Calendar.MILLISECOND, 0);
0
source

Source: https://habr.com/ru/post/1670723/


All Articles