码迷,mamicode.com
首页 > 编程语言 > 详细

c++11 输出时间

时间:2015-09-09 21:04:55      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

C++11中输出当前时间最直接的方法:

std::time_t t2 = std::time(nullptr);
cout << std::put_time(std::localtime(&t), "%Y-%m-%d %H.%M.%S") << "." << msecs << endl;

 

这种方法可以输出年月日时分秒,不过却不能输出毫秒,如果要输出毫秒需要用下面的方法:

auto n = chrono::system_clock::now();
auto m = n.time_since_epoch();
auto diff = duration_cast<milliseconds>(ms).count();
auto const msecs = diff % 1000;

std::time_t t = system_clock::to_time_t(n1);
cout << std::put_time(std::localtime(&t), "%Y-%m-%d %H.%M.%S") << "." << msecs << endl;


将绝对时间转换为标准时间字符串的方法:

string millisecond_to_str(std::int64_t milliseconds)
{
    chrono::milliseconds ms(milliseconds);
    time_point<high_resolution_clock, chrono::milliseconds> t1(ms);
    std::time_t t = system_clock::to_time_t(t1);

    std::stringstream ss;
    auto const msecs = ms.count() % 1000;
    ss << std::put_time(std::localtime(&t), "%Y-%m-%d %H.%M.%S") << "." << msecs;
    return ss.str();
}

 

c++11 输出时间

标签:

原文地址:http://www.cnblogs.com/qicosmos/p/4795664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!