Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a method generic to work with LocalDate and LocalDateTime?

I have a Java method as below:

private static boolean isDateBetweenRange(DataSet obj, MyClass dataSource, ConditionContext context) {
    FilterContext fc = dataSource.getData();

    LocalDate dateFieldToCheck = obj.getDate(fc.getDateField()).toInstant()
                                   .atZone(ZoneId.systemDefault()).toLocalDate();
    LocalDate minDate = fc.getMinDateValue();
    LocalDate maxDate = fc.getMaxDateValue();

    if (minDate == null || maxDate == null) {
        minDate = context.getStartDate().toInstant().atZone(ZoneId.systemDefault())
                    .toLocalDate();
        maxDate = context.getEndDate().toInstant().atZone(ZoneId.systemDefault())
                    .toLocalDate();
    }

    boolean result = (dateFieldToCheck.isAfter(minDate) || dateFieldToCheck.isEqual(minDate))
            && (dateFieldToCheck.isBefore(maxDate) || dateFieldToCheck.isEqual(maxDate));

    return result;
}

I want to make the same logic for LocalDateTime also. It's gonna be the exact same code for LocalDateTime if I overload the method.

How can make the method generic to work with LocalDate and LocalDateTime using Generics or any other mechanism?

How can I make context.getXXXDate()... toLocalDate() or toLocalDateTime() a common code based on type I have?

like image 680
Ajeetkumar Avatar asked Jan 22 '26 12:01

Ajeetkumar


1 Answers

The TemporalAccessor interface can be used to do this. However, be aware that TemporalAccessor is an advanced interface that should not be used outside low-level utility code.

boolean api(TemporalAccessor temporal1, TemporalAccessor temporal2) {
  LocalDate date1 = LocalDate.from(temporal1);
  LocalDate date2 = LocalDate.from(temporal2);
  return ...;
}

This code will now accept LocalDate, LocalDateTime, OffsetDateTime and , ZonedDateTime.

As mentioned in the comments, it is vital to only call ZoneId.systemDefault() once within a piece of business logic, as the value can change.

like image 147
JodaStephen Avatar answered Jan 25 '26 21:01

JodaStephen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!