本文介绍了如何将 std::chrono::time_point 转换为带小数秒的日历日期时间字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
如何将 std::chrono::time_point
转换为带小数秒的日历日期时间字符串?
How to convert std::chrono::time_point
to calendar datetime string with fractional seconds?
例如:
"10-10-2012 12:38:40.123456"
推荐答案
如果是system_clock,这个类有time_t转换.
If system_clock, this class have time_t conversion.
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std::chrono;
int main()
{
system_clock::time_point p = system_clock::now();
std::time_t t = system_clock::to_time_t(p);
std::cout << std::ctime(&t) << std::endl; // for example : Tue Sep 27 14:21:13 2011
}
示例结果:
Thu Oct 11 19:10:24 2012
但是, time_t 不包含小数秒.另一种方法是使用 time_point::time_since_epoch() 函数.此函数返回纪元的持续时间.下面的例子是毫秒分辨率的小数.
But, time_t does not contain fractional seconds. Alternative way is to use time_point::time_since_epoch() function. This function returns duration from epoch. Follow example is milli second resolution's fractional.
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std::chrono;
int main()
{
high_resolution_clock::time_point p = high_resolution_clock::now();
milliseconds ms = duration_cast<milliseconds>(p.time_since_epoch());
seconds s = duration_cast<seconds>(ms);
std::time_t t = s.count();
std::size_t fractional_seconds = ms.count() % 1000;
std::cout << std::ctime(&t) << std::endl;
std::cout << fractional_seconds << std::endl;
}
示例结果:
Thu Oct 11 19:10:24 2012
925
这篇关于如何将 std::chrono::time_point 转换为带小数秒的日历日期时间字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!