[英]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? 为此有一个STL函数吗? 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::). 编译时我遇到了一些小问题(我必须删除所有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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.