from..to
ranges of values. The convention is that
from
is included, while to
is excluded.
Some examples from the JDK:
String.substring(from, to)
List.sublist(from, to)
Arrays.copyOfRange(T[], from, to)
Date Ranges
A related issue is specific to date values.
It's common to have a date range specified using dates only (with no time portion), while the underlying data actually includes both a date and a time.
This can easily lead to off-by-one errors.
For example, taking the following expression:
2010-01-01 <= x <= 2010-01-31then the following is true:
Date x | In Range? |
---|---|
2010-01-01 00:00:00 | Y |
2010-01-01 01:00:00 | Y |
2010-01-30 00:00:00 | Y |
2010-01-30 23:59:59 | Y |
2010-01-31 00:00:00 | Y (usually) |
2010-01-31 00:00:01 | N |
2010-01-31 02:00:00 | N |
(The caveat for 2010-01-31 00:00:00
is made since it will depend on the details of how the comparison is made by the class which models the date/time - usually, it will be within the range.)
The above table shows that times after 2010-01-31 00:00:00
are excluded from the range. This is usually not desirable.
In this case, you need to alter the comparison slighty to:
2010-01-01 <= x < (2010-01-31 + 1 day)
Again, this uses the include-from, exclude-to style mentioned above.