【问题标题】:How to convert chrono::seconds to string in HH:MM:SS format in C++?如何在 C++ 中将 chrono::seconds 转换为 HH:MM:SS 格式的字符串?
【发布时间】:2020-02-03 19:44:49
【问题描述】:

我有一个函数,它接受第二个作为参数并返回 HH:MM:SS 格式的字符串。没有std::chrono,我可以这样实现:

string myclass::ElapsedTime(long secs) {
  uint32_t hh = secs / 3600;
  uint32_t mm = (secs % 3600) / 60;
  uint32_t ss = (secs % 3600) % 60;
  char timestring[9];
  sprintf(timestring, "%02d:%02d:%02d", hh,mm,ss);
  return string(timestring);
}

使用std::chrono,我可以将参数转换为std::chrono::seconds sec {seconds};

但是我怎样才能将它转换为具有格式的字符串呢? 我在 https://youtu.be/P32hvk8b13M 中看到了 Howard Hinnant 的精彩视频教程。不幸的是,没有这个案例的例子。

【问题讨论】:

    标签: c++ c++17 chrono


    【解决方案1】:

    使用Howard Hinnant's header-only date.h library 看起来像这样:

    #include "date/date.h"
    #include <string>
    
    std::string
    ElapsedTime(std::chrono::seconds secs)
    {
        return date::format("%T", secs);
    }
    

    如果你想自己写,那么它看起来更像:

    #include <chrono>
    #include <string>
    
    std::string
    ElapsedTime(std::chrono::seconds secs)
    {
        using namespace std;
        using namespace std::chrono;
        bool neg = secs < 0s;
        if (neg)
            secs = -secs;
        auto h = duration_cast<hours>(secs);
        secs -= h;
        auto m = duration_cast<minutes>(secs);
        secs -= m;
        std::string result;
        if (neg)
            result.push_back('-');
        if (h < 10h)
            result.push_back('0');
        result += to_string(h/1h);
        result += ':';
        if (m < 10min)
            result.push_back('0');
        result += to_string(m/1min);
        result += ':';
        if (secs < 10s)
            result.push_back('0');
        result += to_string(secs/1s);
        return result;
    }
    

    在 C++20 中,你可以说:

    std::string
    ElapsedTime(std::chrono::seconds secs)
    {
        return std::format("{:%T}", secs);
    }
    

    【讨论】:

      【解决方案2】:

      一旦 C++20 实现落地,您将能够执行以下操作(未经测试的代码):

      std::chrono::hh_mm_ss<std::chrono::seconds> tod{std::chrono::seconds(secs)};
      std::cout << tod;
      

      请参阅time.hms.overview 了解更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-06
        • 2020-08-07
        相关资源
        最近更新 更多