简体   繁体   中英

Java compare two Dates Year, month and day

I have a method to compare two dates to see if transactionDate is in range between validFrom and validUntil, validFrom and validUnti has value like "2017-01-01 00:00:00" but the transaction date sometimes comes with different hours due to conversion to different timezone.

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 compare only Year Month and day and don't take time into account, what would be most efficient way without transforming date to gregorianCalendar and geting year month and day separately?

LocalDate

I think the easy solution is to convert to LocalDate :

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

The LocalDate class accepts parsing with a pattern that includes hours, minutes and seconds, it just ignores those values from the string.

Do the same with validUntil and the transaction date. Compare the resulting LocalDate instances using isBefore() , isAfter() , isEqual() , or compareTo() .

If you were using Java < 8, unfortunately there would have been no simple answer (ie you'd have to use Calendar as you said in your question, or maybe rely on a third-party library like Joda-Time).

Hopefully you use Java 8, so we can leverage the goodness that is the java.time package. Since you want to just compare dates (not times), and do not care about timezones, what you want to use is 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);
}

You can use Calendar and set the other parameters apart from year, month and day 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM