天天看点

C++11日期时间显示(精确到毫秒)

C++11中提供了方便时间操作的chrono库(参见C++11时间日期库chrono简介),但是其输出显示并不方便;通过put_time可以显示时间(到秒),要显示毫秒,就需要自己处理了。

使用duration_cast可以把时间点转换为不同的形式(并把时间截断为对应的精度);因此,通过把要显示的时间转换为毫秒与秒,然后求其之间的差值,就能得到所需的毫秒。

#include <ctime>
#include <chrono>
#include <string>
#include <sstream>
#include <iomanip>

// 时间字符串(如:2020-05-02 14:40:31.015)
std::string getTimeString(bool bLocal, bool bIncludeMS) {
    auto tNow = std::chrono::system_clock::now();
    //auto tmNow = std::chrono::system_clock::to_time_t(tNow);
    auto tSeconds = std::chrono::duration_cast<std::chrono::seconds>(tNow.time_since_epoch());
    auto secNow = tSeconds.count();
    tm tmNow;
    if (bLocal) {
        localtime_s(&tmNow, &secNow);
    }
    else {
        gmtime_s(&tmNow, &secNow);
    }

    std::ostringstream oss;
    oss << std::put_time(&tmNow, "%Y-%m-%d %H:%M:%S");
    if (bIncludeMS) {
        auto tMilli = std::chrono::duration_cast<std::chrono::milliseconds>(tNow.time_since_epoch());
        auto ms = tMilli - tSeconds;
        oss << "." << std::setfill('0') << std::setw(3) << ms.count();
    }

    return oss.str();
}