如何在C++11中找到两个日期之间的时间持续时间(小时-分-秒)



我需要找到两个给定日期之间的时间差。

我尝试了以下代码,但无法将其转换为小时-分钟-秒

const char *time_details = "06/10/2021 16:35:12";
struct tm tm;
strptime(time_details, "%m/%d/%Y %H:%M:%S", &tm); // Prev date
time_t t = mktime(&tm);
const char *time_details1 = "06/11/2021 14:35:12";
struct tm tm1;
strptime(time_details1, "%m/%d/%Y %H:%M:%S", &tm1); // future date
time_t t33 = mktime(&tm1);
int timediff1 = difftime(t33,t);
int seconds1 = timediff1%60;
int hour1 =seconds1/ 3600;
int minutes1 = seconds1 / 60 ;

上面总是以小时-分钟-秒显示"0"。但在中获得一些价值

有了C++2a的早期支持,您可以执行类似的操作

std::tm tm1 = {}, tm2 = {};
std::stringstream ss("06/10/2021 16:35:12 06/11/2021 14:35:12");
ss >> std::get_time(&tm1, "%m/%d/%Y %H:%M:%S");
ss >> std::get_time(&tm2, "%m/%d/%Y %H:%M:%S");
auto tp1 = std::chrono::system_clock::from_time_t(std::mktime(&tm1));
auto tp2 = std::chrono::system_clock::from_time_t(std::mktime(&tm2));
auto diff = tp2 - tp1;
// convert to human-readable form
auto d = std::chrono::duration_cast<std::chrono::days>(diff);
diff -= d;
auto h = std::chrono::duration_cast<std::chrono::hours>(diff);
diff -= h;
auto m = std::chrono::duration_cast<std::chrono::minutes>(diff);
diff -= m;
auto s = std::chrono::duration_cast<std::chrono::seconds>(diff);
std::cout << std::setw(2) << d.count() << "d:"
<< std::setw(2) << h.count() << "h:"
<< std::setw(2) << m.count() << "m:"
<< std::setw(2) << s.count() << 's';

并且完全支持operator<<用于duration类。对于C++11,std::chrono::dayshours必须用等价物代替,例如duration<int, std::ratio<86400>>代替days

试试这个

void computeTimeDiff(struct TIME t1, struct TIME t2, struct TIME *difference){

if(t2.seconds > t1.seconds)
{
--t1.minutes;
t1.seconds += 60;
}
difference->seconds = t1.seconds - t2.seconds;
if(t2.minutes > t1.minutes)
{
--t1.hours;
t1.minutes += 60;
}
difference->minutes = t1.minutes-t2.minutes;
difference->hours = t1.hours-t2.hours;
}

最新更新