How to calculate the date six months from the current date in C++

2 Answers

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

int main() {
    // Get the current date
    auto today = std::chrono::system_clock::now();
    auto today_time_t = std::chrono::system_clock::to_time_t(today);
    std::tm today_tm = *std::localtime(&today_time_t);

    // Add six months to the current date
    today_tm.tm_mon += 6;

    // Normalize the date (handles overflow of months into years)
    std::mktime(&today_tm);

    // Print the new date
    std::cout << "Date six months from now: "
              << std::put_time(&today_tm, "%Y-%m-%d") << std::endl;
}



/*
run:

Date six months from now: 2025-12-11

*/

 



answered Jun 11 by avibootz
0 votes
#include <iostream>
#include <chrono>
#include <iomanip>

// Function to calculate future date by adding given months
std::tm calculateFutureDate(int monthsToAdd) {
    auto today = std::chrono::system_clock::now();
    auto today_time_t = std::chrono::system_clock::to_time_t(today);
    std::tm today_tm = *std::localtime(&today_time_t);

    // Add months
    today_tm.tm_mon += monthsToAdd;

    // Normalize the date (handles overflow of months into years)
    std::mktime(&today_tm);

    return today_tm;  // Return the modified date
}

int main() {
    std::tm futureDate = calculateFutureDate(6);

    // Print the new date
    std::cout << "Date six months from now: "
              << std::put_time(&futureDate, "%Y-%m-%d") << std::endl;
}



/*
run:

Date six months from now: 2025-12-11

*/

 



answered Jun 11 by avibootz
edited Jun 11 by avibootz
...