3

I am trying to check if a particular date falls within a certain date range. I came across Joda Time interval in Java. But it works as end time exclusive.

So is there an alternative which functions as end time inclusive

Ann
  • 137
  • 1
  • 11
  • 1
    What's your exact use case? Can you describe it a little more in detail? Or could you show us the code with joda that doesn't do what's desired? – deHaar Jun 14 '21 at 10:37
  • 1
    See this answer: https://stackoverflow.com/a/13584000/8621733 Strict `<` can be negated to `>=` so this might be useful. – Artúr Manó Marschal Jun 14 '21 at 10:41
  • Does your date have year, month of year and day of month only or are you talking about a `java.util.Date`? – deHaar Jun 14 '21 at 10:54
  • 1
    Read this post, it contains great info on how to use java.time: https://stackoverflow.com/questions/32437550/whats-the-difference-between-instant-and-localdatetime – DigitShifter Jun 14 '21 at 13:54

1 Answers1

7

java.time

I recommend you use modern Date-Time API*.

Quoted below is a notice at the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

You can use !date.isAfter where date is a reference to LocalDate e.g.

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2021, 5, 10);
        LocalDate end = LocalDate.of(2021, 6, 10);
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            // ...
        }
    }
}

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 4
    Solid Answer. Further tip: The [`LocalDateRange`](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/LocalDateRange.html) class in the [*ThreeTen-Extra*](https://www.threeten.org/threeten-extra/) library has methods to treat the ending as inclusive, using "closed" terminology, as in full-closed versus half-open. But I recommend always working with half-open to keep your logic consistent. I have seen many miscommunications amongst businesspeople regarding fully-closed versus half-open. And, using half-open enables time spans that neatly abut. – Basil Bourque Jun 14 '21 at 21:12