How to add N weeks to a given date in C++

1 Answer

0 votes
#include <iostream>
#include <chrono>

/**
 * Adds a specified number of weeks to a given year_month_day date.
 * 
 * @param ymd   The base date as std::chrono::year_month_day.
 * @param weeks The number of weeks to add (can also be negative to subtract).
 * @return      The resulting date as std::chrono::year_month_day.
 */
std::chrono::year_month_day add_weeks_to_date(std::chrono::year_month_day ymd, int weeks) {
    // 1. Validate that the input date is a valid calendar date before doing math.
    if (!ymd.ok()) {
        throw std::invalid_argument("Invalid base date provided.");
    }

    // 2. Convert year_month_day to sys_days (a count of days since the epoch).
    std::chrono::sys_days dp{ymd};

    // 3. Add the weeks. std::chrono::weeks automatically scales to weeks * 7 days.
    dp += std::chrono::weeks(weeks);

    // 4. Convert back to year_month_day. This automatically recalculates 
    // the correct year, month, and day, handling all rollover logic safely.
    return std::chrono::year_month_day{dp};
}

int main() {
    // Initialize a sample date: November 8, 2026 using C++20 chrono syntax
    std::chrono::year_month_day target_date = std::chrono::year(2026) / 11 / 8;

    int weeks_to_add = 4;

    try {
        std::chrono::year_month_day result_date = add_weeks_to_date(target_date, weeks_to_add);

        std::cout << "Original date: " << target_date << '\n';
        std::cout << "After adding " << weeks_to_add << " weeks: " << result_date << '\n';
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << '\n';
    }
}


/*
run:

Original date: 2026-11-08
After adding 4 weeks: 2026-12-06

*/

 



answered 18 hours ago by avibootz
...