博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++11日期时间显示(精确到毫秒)
阅读量:2055 次
发布时间:2019-04-28

本文共 949 字,大约阅读时间需要 3 分钟。

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

转载地址:http://ygnlf.baihongyu.com/

你可能感兴趣的文章
【托业】【跨栏】REVIEW2
查看>>
Javascript的RegExp对象(转载自网络)
查看>>
rwx对于文件和目录的意义
查看>>
借助csv用PHP生成excel文件
查看>>
使用SimpleXML解析xml文件数据
查看>>
php读取excel文档内容(转载)
查看>>
vim基本命令(转载自网络)
查看>>
Linux学习(二十二)Shell基础(二)变量、环境变量配置文件
查看>>
Linux学习(二十四)正则表达式(二)sed
查看>>
Linux学习(二十三)正则表达式(一)grep/egrep
查看>>
Linux学习(二十六)日常管理(一)w、vmstat、top、sar、nload、iostat、iotop
查看>>
Linux学习(二十五)正则表达式(三)awk
查看>>
js和php写日历
查看>>
shell递归遍历目录的方法
查看>>
https改造过程中的一个坑
查看>>
GitLab 实现代码自动部署(转载自https://segmentfault.com/a/1190000011561808)
查看>>
free命令详解(转载)
查看>>
tcp协议端口解释(转载)
查看>>
三次挥手四次挥手(转载)
查看>>
keepalived
查看>>