How to format std::chrono durations?

前端 未结 4 1763
名媛妹妹
名媛妹妹 2021-01-11 12:49

Is there a convenient way to format std::chrono::duration to a specified format?

std::chrono::high_resolution_clock::time_point now, then;
then          


        
4条回答
  •  执笔经年
    2021-01-11 13:11

    Here is a possible solution using a variadic template.
    The if constexpr () makes it c++17 only but replacing with a regular if still works and is c++14 compliant.

    template
    std::string formatDuration(DurationIn d)
    {   
        auto val = std::chrono::duration_cast(d);
    
        string out = std::to_string(val.count());
    
        if constexpr(sizeof...(RestDurations) > 0) {
            out += "::" + formatDuration(d - val);
        }
    
        return out;
    }
    
    template
    std::string formatDuration(DurationIn) { return {}; } // recursion termination
    

    testing in main, outputs "77::600::42"

    auto formattedStr = formatDuration<
        std::chrono::microseconds,
        std::chrono::seconds,
        std::chrono::milliseconds,
        std::chrono::microseconds>(77'600'042us);
    

提交回复
热议问题