java.time - Is there a function to find number of a specific day (day of week, or day of month) between two days?

Azzam Alsharafi :

So is there a function or something which you give two dates and a day of week (ex. Saturday) and it returns the number of Saturdays between the two dates?

The problem with trying to use ChronoUnit.WEEKS.between and dividing the result by 7 is that it won't work if you have something like 4 days (because it's not a full week), or 10 days (because it'll be counted as one week).

Another idea maybe to use a loop and check if a day is Saturday, but this way is inefficient and slow for large time ranges.

What about a similar function but rather than a day of week, it counts the occurrences of a day of month (ex. 15th of any month), or a day of year (ex. April 4th of any year).

If there are no such functions, what may be an efficient way to do this?

Basil Bourque :

As others commented, you need to write your own code. But java.time and Java Streams get you most of the way.

The LocalDate::datesUntil method generates a stream of LocalDate objects. Test each for its DayOfWeek. Collect the hits.

Something like this untested example code.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate start = LocalDate.now( z ) ;
LocalDate then = today.plusDays( 177 ) ;
Stream < LocalDate > dates = start.datesUntil( then ) ;
List < LocalDate > saturdays = 
        dates
        .filter( 
            date -> 
                date
                .getDayOfWeek()
                .equals( DayOfWeek.SATURDAY ) 
        )
        .collect( 
            Collectors.toList()
        )
; 

You expressed a concern about efficiency. I suspect you are falling into the trap of premature optimization. Is your app really performing this operation thousands of times per minute all day? If not, performance is likely not a problem.

Always write simple straightforward code first. Then test empirically with the Microbenchmarks Suite and with a profiler to see if your concerns are valid.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19172&siteId=1