How to calculate the number of weekdays between two dates in Java

1 Answer

0 votes
import java.time.DayOfWeek;
import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        System.out.println(countWeekDays(LocalDate.of(2025, 1, 1), LocalDate.of(2025, 1, 7)));
        System.out.println(countWeekDays(LocalDate.of(2025, 2, 1), LocalDate.of(2025, 2, 10)));
        System.out.println(countWeekDays(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 12, 31)));
        System.out.println(countWeekDays(LocalDate.of(2025, 1, 1), LocalDate.of(2025, 12, 31)));
    }

    public static int countWeekDays(LocalDate d1, LocalDate d2) {
        long ndays = 1 + java.time.temporal.ChronoUnit.DAYS.between(d1, d2);
        int nsaturdays = (int) (ndays + d1.getDayOfWeek().getValue()) / 7;

        return (int) ndays - 2 * nsaturdays
                - (d1.getDayOfWeek() == DayOfWeek.SUNDAY ? 1 : 0)
                + (d2.getDayOfWeek() == DayOfWeek.SATURDAY ? 1 : 0);
    }
}


   
   
/*
run:
   
5
6
262
261
  
*/


 



answered Feb 18, 2025 by avibootz

Related questions

1 answer 93 views
1 answer 85 views
1 answer 111 views
1 answer 80 views
1 answer 96 views
3 answers 324 views
2 answers 94 views
...