How to find the dates of the last Sunday of each month of a given year in C++

1 Answer

0 votes
#include <chrono>
#include <iostream>
 
using namespace std::chrono;
 
// Return the last Sunday of a specific month
year_month_day last_sunday_of_month(int y, unsigned m) {
    year_month ym{year{y}, month{m}};
 
    // First day of next month
    year_month_day first_next = (ym + months{1}) / day{1};
 
    // Last day of this month
    sys_days last_day = sys_days{first_next} - days{1};
 
    // Walk backward to Sunday
    while (weekday{last_day} != Sunday) {
        last_day -= days{1};
    }
 
    return year_month_day{last_day};
}
 
// Print all last Sundays of each month in a given year
void list_of_last_sundays_of_each_month_in(int year) {
    for (unsigned m = 1; m <= 12; m++) {
        year_month_day d = last_sunday_of_month(year, m);
        std::cout << (int)d.year() << "-"
             << (unsigned)d.month() << "-"
             << (unsigned)d.day() << "\n";
    }
}
 
int main(int argc, char *argv[]) {
    int year = (argc > 1)
        ? std::stoi(argv[1])
        : 2026;

    list_of_last_sundays_of_each_month_in(year);
}
 
 
 
/*
run:
 
2026-1-25
2026-2-22
2026-3-29
2026-4-26
2026-5-31
2026-6-28
2026-7-26
2026-8-30
2026-9-27
2026-10-25
2026-11-29
2026-12-27
 
*/

 



answered May 23 by avibootz
edited May 24 by avibootz

Related questions

...