Java date and time (JSR 310): time range contains value without iterating all of them

I have a custom range (~ Collection) that has 2 Temporalbounds ( fromand to) and can list all values ​​between these 2 borders in time, increasing with the given TemporalUnit incrementUnitType.

private final Temporal_ from;
private final Temporal_ to;
private final TemporalUnit incrementUnitType; // For example Month, Day,  Minute, ...

In it, I need to implement the contains method to check if iteration through this range will contain a specific value. For example, if it contains March 8th. Here is how I would like to write this method:

public boolean contains(Temporal_ value) {
    ...
    if (from.until(value, incrementUnitType) < 0
            || value.until(to, incrementUnitType) <= 0) {
        return false; // Out of bounds
    }
    // This doesn't work because 1-MAR + 1 month doesn't include 8-MAR
    return true;
}

Here are a few iterations:

  • from - to (incrementUnitType)
  • 1-MAR - 10-APR (1 day): 1-MAR, 2-MAR, 3-MAR, 4-MAR, ..., 8-APR, 9-APR
  • 1-MAR - 10-APR (1 week) : 1-MAR, 8-MAR, 15-MAR, 22-MAR, 29-MAR, 5-APR
  • 1-MAR - 10-APR (1 ): 1-MAR, 1-APR

true 8-MAR . , , for :

public boolean contains(Temporal_ value) {
    ...
    if (from.until(value, incrementUnitType) < 0
            || value.until(to, incrementUnitType) <= 0) {
        return false; // Out of bounds
    }
    // This works but it kills scalability
    for (long i = 0; i < getSize(); i++) {
        Temporal_ temporal = get(i);
        if (value.equals(temporal)) {
            return true;
        }
    }
    return false;
}

. ?

+4
2

Temporal.until, . " " (doc), from , .

long wholeAmount = from.until(value, incrementUnitType)
return value.equals(from.plus(wholeAmount, incrementUnitType));

, , (, 28, 29, 30 31 ). until plus (.. temporal.until(temporal.plus(1,ChronoUnit.MONTHS),ChronoUnit.MONTHS) 0, ).

doc:

. , - 31 , . . , ​​ .

, wholeAmount + 1, , .

// ... out of bound check
// ...
long wholeAmount = from.until(value, incrementUnitType)
return value.equals(from.plus(wholeAmount, incrementUnitType)) || value.equals(from.plus(wholeAmount + 1, incrementUnitType));

Temporal , , ( , incrementUnitType ). , , .

+3

.

  • DAYS , .
  • WEEKS toEpochDays() , , 7
  • MONTHS ,

Temporal , , . , LocalDate.from(temporal) , LocalDate.

+2

All Articles