简体   繁体   中英

How do I represent a time difference in an `std::time_t` variable as days, hours, minutes and seconds?

I want to find the time difference between now and a given date in days, hours, minutes and seconds.

std::tm                 tm_Trg;
tm_Trg.tm_year          = 120;                  // 2020
tm_Trg.tm_mon           = 4;                    // May
tm_Trg.tm_mday          = 15;                   // 15th
tm_Trg.tm_hour          = 11;                   // 11:35:13
tm_Trg.tm_min           = 35;
tm_Trg.tm_sec           = 13;
tm_Trg.tm_isdst         = -1;
std::time_t             tt_Now;
std::time_t             tt_Trg;
std::time_t             tt_Dif;
tt_Now                  = std::time(nullptr);
tt_Trg                  = std::mktime(&tm_Trg);
tt_Dif                  = tt_Trg - tt_Now;
// ...
int nDays               = ???
int nHours              = ???
int nMinutes            = ???
int nSeconds            = ???

Is there an STL function for this? If not, what is the simplest algorithm for this conversion?

I had a few minor issues when compiling (I had to remove all instances of std::).

The remaining part isn't exactly what you want (you get years and days, rather than just days), but if you really want to use library functions for some reason:

struct tm *timeinfo     = gmtime(&tt_Dif);
int nYears              = timeinfo->tm_year - 70;
int nDays               = timeinfo->tm_yday;
int nHours              = timeinfo->tm_hour;
int nMinutes            = timeinfo->tm_min;
int nSeconds            = timeinfo->tm_sec;

printf("nYears:\t%d\nnDays:\t%d\nnHours:\t%d\nnMinutes:\t%d\nnSeconds:\t%d\n", nYears, nDays, nHours, nMinutes, nSeconds);

Otherwise, a pretty simple way to get the result is:

int nSeconds            = tt_Dif % 60;  tt_Dif /= 60;
int nMinutes            = tt_Dif % 60;  tt_Dif /= 60;
int nHours              = tt_Dif % 24;  tt_Dif /= 24;
int nDays               = tt_Dif;

printf("nDays:\t%d\nnHours:\t%d\nnMinutes:\t%d\nnSeconds:\t%d\n", nDays, nHours, nMinutes, nSeconds);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM