When it comes to Period
s, -
is not supposed to be the inverse of +
: adding one month to March 31 produces April 30. Subtracting one month from April 30 produces March 30, not March 31.
I've got a filter on database records that involves periods:
priorDate + period < today
Here, priorDate
is derived from a database column, period
can be configured by the user, and I need to find all records for which the condition is true.
If the period doesn't involve months or years, I can transform this into
priorDate < today - period
which allows the comparison to be moved from the client side to the database: it allows me to avoid retrieving all records just to discard the ones that don't meet the criteria.
How do I do this if the period does involve months or years?
I can assume the Gregorian calendar, and that that period
is non-negative. (Specifically: I can assume priorDate + period >= priorDate
for all values of priorDate
, but if possible, I'd like to not rule out periods "one month minus one day" just yet.)
If I've got a period of one month, and today is April 30, then I want to figure out that the expression should become priorDate < new LocalDate(2018, 3, 30)
, which is easy: that's what today - period
produces.
If I've got a period of one month, and today is March 30 2018, then today - period
will produce February 28, but the expression should instead become a comparison to March 1: if priorDate
is exactly new LocalDate(2018, 2, 28)
, then priorDate + period < new LocalDate(2018, 3, 30)
will be true, but priorDate < new LocalDate(2018, 2, 28)
will be false.