C++11中提供了方便时间操作的chrono库(参见C++11时间日期库chrono简介),但是其输出显示并不方便;通过put_time可以显示时间(到秒),要显示毫秒,就需要自己处理了。
使用duration_cast可以把时间点转换为不同的形式(并把时间截断为对应的精度);因此,通过把要显示的时间转换为毫秒与秒,然后求其之间的差值,就能得到所需的毫秒。
#include
#include
#include
#include
#include
// 时间字符串(如: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(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 |