Skip to content
Advertisement

Java 8 calculate how many 1st of the months between two dates

I have two dates:

Start date: "2022-03-14"
End date: "2022-04-15"

I want the result = 1 (for the date, 2022-04-01)

Advertisement

Answer

tl;dr

LocalDate.parse( "2022-03-14" ).datesUntil( LocalDate.parse( "2022-04-15" ) ).filter( localDate -> localDate.getDayOfMonth() == 1 ).count()

See this code run live at IdeOne.com.

1

Details

First, parse the inputs as LocalDate objects.

LocalDate start = LocalDate.parse( "2022-03-14" );
LocalDate end = LocalDate.parse( "2022-04-15" );

The LocalDate#datesUntil method creates a stream of LocalDate objects between the two values. We can filter that stream to keep only the ones whose day-of-month is 1 (the first of the month). Then we ask for a count of those filtered objects.

long countFirstOfMonths =
        start
                .datesUntil( end )
                .filter( localDate -> localDate.getDayOfMonth() == 1 )
                .count();

Report.

String message = String.format( "From %s to %s contains %d first-of-month dates." , start.toString() , end.toString() , countFirstOfMonths );
System.out.println( message );
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement