How to calculate the number of weekdays in the current year with Java

2 Answers

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

public class Main {
    public static void main(String[] args) {
        int year = LocalDate.now().getYear();
        int weekdayCount = countWeekdaysInYear(year);
        
        System.out.println("Number of weekdays in " + year + ": " + weekdayCount);
    }

    static int countWeekdaysInYear(int year) {
        int weekdayCount = 0;

        LocalDate date = LocalDate.of(year, 1, 1);
        while (date.getYear() == year) {
            if (date.getDayOfWeek() != DayOfWeek.SATURDAY && date.getDayOfWeek() != DayOfWeek.SUNDAY) {
                weekdayCount++;
            }
            date = date.plusDays(1);
        }

        return weekdayCount;
    }
}

   
   
/*
run:
   
Number of weekdays in 2025: 261
  
*/

 



answered Feb 18, 2025 by avibootz
0 votes
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Year;

public class Main {
    public static void main(String[] args) {
        int currentYear = Year.now().getValue();
        LocalDate startDate = LocalDate.of(currentYear, 1, 1);
        LocalDate endDate = LocalDate.of(currentYear, 12, 31);

        int weekdayCount = 0;

        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            DayOfWeek dayOfWeek = date.getDayOfWeek();
            if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
                weekdayCount++;
            }
        }

        System.out.println("Number of weekdays in " + currentYear + ": " + weekdayCount);
    }
}

   
   
/*
run:
   
Number of weekdays in 2025: 261
  
*/


 



answered Feb 18, 2025 by avibootz

Related questions

1 answer 154 views
1 answer 80 views
1 answer 88 views
1 answer 105 views
2 answers 77 views
1 answer 101 views
1 answer 105 views
...