Harry
Harry

Reputation: 109

Java Date Object List interval checking

I have a bunch of date objects (20 of them) in a list and I want to know if each date is between two date intervals i.e. startdate = 2005-09 and enddate = 2009-07

How can I check these conditions?

List<DateObject> myDates = new ArrayList<>();

DateObject dates = new DateObject("1990-05-19,");
        mydatesDates.add(dates);

dates = new DateObject("2004-07-25");
        myDates.add(dates);

...and this pattern goes on for about 20 dates

Upvotes: 2

Views: 469

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 339442

LocalDate

Use the LocalDate class to represent a date-only value without a time-of-day and without a time zone.

LocalDate ld = LocalDate.parse( "1990-05-19" );

Collect this into a List.

List<LocalDate> dates = new ArrayList<>(); // Pass an initialCapacity argument if you have one.
dates.add( ld ); // Repeat for all your `LocalDate` objects.

YearMonth

For comparison you seem to care only about year-month. You can use the YearMonth class for that.

YearMonth start = YearMonth.of( 2005 , 9 ); // Or pass Month.SEPTEMBER
YearMonth stop = YearMonth.of( 2009, 7 ); // Or pass Month.JULY

Loop the list to see if any one of them is too early or too late.

List<LocalDate> tooEarly = new ArrayList<>();
List<LocalDate> tooLate = new ArrayList<>();
List<LocalDate> justRight = new ArrayList<>();

for (String date : dates) {
    YearMonth ym = YearMonth.from( date );
    if( ym.isBefore( start ) ) {
        tooEarly.add( date );
    } else if( ! ym.isBefore( stop ) ) {  // Using Half-Open approach where ending is *exclusive*. Use “( ym.isAfter( stop ) )” if you want inclusive ending.
        tooLate.add( date );
    } else {
        justRight.add( date );
    }
    System.out.println( "ERROR unexpectedly went beyond the if-else-else." ); 
}

Upvotes: 1

You can use a stream and for checking the date the methods Date#before() and Date#after()

Example:

List<Date> myDates = new ArrayList<>();
Date begin = ...//your date here;
Date end = ...//your date here;
List<Date> result = myDates.stream().filter(x -> x.after(begin) && x.before(end)).collect(Collectors.toList());
// now print it
result.forEach(System.out::println);

Upvotes: 1

Related Questions