How to calculate the number of weekdays in the current year with C++

1 Answer

0 votes
#include <iostream>
#include <ctime>

int getCurrentYear() {
    std::time_t t = std::time(nullptr);
     
    std::tm *const localtime = std::localtime(&t);
     
    return localtime->tm_year + 1900;
}

bool isWeekday(int year, int month, int day) {
    std::tm time_in = { 0, 0, 0, day, month - 1, year - 1900 };
    std::mktime(&time_in);
    int wday = time_in.tm_wday;
    
    return (wday != 0 && wday != 6); // 0 = Sunday, 6 = Saturday
}

int countWeekdays(int year) {
    int weekdays = 0;
    
    for (int month = 1; month <= 12; month++) {
        for (int day = 1; day <= 31; day++) {
            std::tm time_in = { 0, 0, 0, day, month - 1, year - 1900 };
            if (std::mktime(&time_in) != -1 && time_in.tm_mon == month - 1) {
                if (isWeekday(year, month, day)) {
                    ++weekdays;
                }
            }
        }
    }
    
    return weekdays;
}

int main() {
    int currentYear = getCurrentYear();
    
    int weekdays = countWeekdays(currentYear);
    
    std::cout << "Number of weekdays in " << currentYear << " is: " << weekdays << std::endl;
}


/*
run:

Number of weekdays in 2025 is: 261

*/

 



answered Feb 18, 2025 by avibootz
edited Feb 18, 2025 by avibootz

Related questions

1 answer 155 views
1 answer 88 views
2 answers 86 views
1 answer 105 views
2 answers 77 views
1 answer 80 views
1 answer 87 views
...