How to convert days into human-readable years, months and days in C++

2 Answers

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

int main() {
    // Difference between Jan 1, 2024 and Mar 27, 2025 (including both days):
    // 1 years 2 months 27 days
    // or 14 months 27 days
    // or 64 weeks 4 days
    // or 452 calendar days

    int days = 452;
    std::tm startDate = {0, 0, 0, 1, 0, 2024 - 1900}; // based on actual days in each month
    std::tm endDate = startDate;
    endDate.tm_mday += days;
    std::mktime(&endDate);

    int years = endDate.tm_year - startDate.tm_year;
    int months = endDate.tm_mon - startDate.tm_mon;
    int daysLeft = endDate.tm_mday - startDate.tm_mday;

    std::cout << years << " years " << months << " months " << daysLeft << " days" << std::endl;
}


 
/*
run:
 
1 years 2 months 27 days
 
*/

 



answered Jun 27, 2024 by avibootz
0 votes
#include <iostream>
#include <tuple>

constexpr int DAYS_PER_YEAR  = 365;
constexpr int DAYS_PER_MONTH = 30;

std::tuple<int, int, int> split_days(int total_days) {
    int years  = total_days / DAYS_PER_YEAR;
    total_days %= DAYS_PER_YEAR;

    int months = total_days / DAYS_PER_MONTH;
    total_days %= DAYS_PER_MONTH;

    int days   = total_days;

    return {years, months, days};
}

int main() {
    auto [y, m, d] = split_days(452);
    
    std::cout << y << " years, " << m << " months, " << d << " days\n";
}



/*
run:

1 years, 2 months, 27 days

*/

 



answered Dec 31, 2025 by avibootz

Related questions

...