【问题标题】:How to find Time Duration between two dates with Hours minutes and seconds in C++ 11?如何在 C++ 11 中使用小时分钟和秒来查找两个日期之间的持续时间?
【发布时间】:2021-08-29 00:48:31
【问题描述】:

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

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

         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++11,那么看看使用 - stackoverflow.com/questions/31657511/…
  • 数学上面的代码应该是这样的:int hour1 = timediff1 / 3600; int minutes1 = timediff1 % 3600 / 60; 因为int seconds1 = timediff1%60 给出的秒数是从 0 到 59,而你显然不能从这个值计算小时和分钟。
  • @dewaffled 谢谢你的帮助。我得到了输出。谢谢
  • @Dean-Jason。谢谢。

标签: c++ visual-studio c++11 mktime time-t


【解决方案1】:

有了 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';

并且为duration 类提供operator&lt;&lt; 的全面支持。对于 C++11,std::chrono::dayshours 必须替换为等价物,例如duration&lt;int, std::ratio&lt;86400&gt;&gt;days

【讨论】:

    【解决方案2】:

    试试这个

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-19
      • 2011-04-19
      • 2020-01-25
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      相关资源
      最近更新 更多