Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

How to turn a total number of seconds into years, months, days, minutes and seconds in C++

1 Answer

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

// Struct to hold the broken-down time units
struct TimeBreakdown {
    long long years;
    long long months;
    long long days;
    long long hours;
    long long minutes;
    long long seconds;
};

// Function to convert total seconds into the TimeBreakdown struct
TimeBreakdown convertSeconds(long long total_input_seconds) {
    using namespace std::chrono;

    // Use C++20 durations for accurate calendar averages
    seconds remaining_secs{total_input_seconds};

    // Calculate Years
    auto y = duration_cast<years>(remaining_secs);
    remaining_secs -= y;

    // Calculate Months
    auto mon = duration_cast<months>(remaining_secs);
    remaining_secs -= mon;

    // Calculate Days
    auto d = duration_cast<days>(remaining_secs);
    remaining_secs -= d;

    // Use hh_mm_ss to easily extract hours, minutes, and seconds from what's left
    hh_mm_ss hms{remaining_secs};

    return {
        y.count(),
        mon.count(),
        d.count(),
        hms.hours().count(),
        hms.minutes().count(),
        (long long)hms.seconds().count()
    };
}

int main() {
    long long input = 102300000; 
    
    TimeBreakdown tb = convertSeconds(input);

    std::cout << "Total Seconds: " << input << "\n";
    std::cout << "Years:   " << tb.years << "\n"
              << "Months:  " << tb.months << "\n"
              << "Days:    " << tb.days << "\n"
              << "Hours:   " << tb.hours << "\n"
              << "Minutes: " << tb.minutes << "\n"
              << "Seconds: " << tb.seconds << std::endl;

    return 0;
}




/*
run:

Total Seconds: 102300000
Years:   3
Months:  2
Days:    27
Hours:   10
Minutes: 14
Seconds: 12

*/

 



answered Jan 21 by avibootz

Related questions

...