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

2 Answers

0 votes
#include <stdio.h>

struct DateParts {
    int years;
    int months;
    int days;
    int hours;
    int minutes;
    int seconds;
};

struct DateParts seconds_to_date_parts(long long total) {
    const int MIN = 60;
    const int HOUR = 60 * MIN;
    const int DAY = 24 * HOUR;
    const int MONTH = 30 * DAY;
    const int YEAR = 365 * DAY;

    struct DateParts b;

    b.years   = total / YEAR;   total %= YEAR;
    b.months  = total / MONTH;  total %= MONTH;
    b.days    = total / DAY;    total %= DAY;
    b.hours   = total / HOUR;   total %= HOUR;
    b.minutes = total / MIN;    total %= MIN;
    b.seconds = total;

    return b;
}

int main() {
    struct DateParts b = seconds_to_date_parts(100000000);
    
    printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds\n",
           b.years, b.months, b.days, b.hours, b.minutes, b.seconds);
}



/*
run:

3 years, 2 months, 2 days, 9 hours, 46 minutes, 40 seconds

*/

 



answered Jan 21 by avibootz
0 votes
#include <stdio.h>
#include <time.h>

struct Breakdown {
    int years;
    int months;
    int days;
    int hours;
    int minutes;
    int seconds;
};

struct Breakdown seconds_to_calendar(long long seconds) {
    struct tm start = {0};
    start.tm_year = 100;  // 2000
    start.tm_mon  = 0;    // January
    start.tm_mday = 1;

    time_t t0 = timegm(&start);
    time_t t1 = t0 + seconds;

    struct tm end;
    gmtime_r(&t1, &end);

    struct Breakdown b;
    b.years   = end.tm_year - start.tm_year;
    b.months  = end.tm_mon  - start.tm_mon;
    b.days    = end.tm_mday - start.tm_mday;
    b.hours   = end.tm_hour;
    b.minutes = end.tm_min;
    b.seconds = end.tm_sec;

    return b;
}

int main() {
    struct Breakdown b = seconds_to_calendar(100000000);
    
    printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds\n",
           b.years, b.months, b.days, b.hours, b.minutes, b.seconds);
}



/*
run:

3 years, 2 months, 2 days, 9 hours, 46 minutes, 40 seconds

*/

 



answered Jan 21 by avibootz

Related questions

...