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 );
solved Java 8 calculate how many 1st of the months between two dates