如何将 std::chrono::time_point 转换为带小数秒的日历日期时间字符串?

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?(如何将 std::chrono::time_point 转换为带小数秒的日历日期时间字符串?)
本文介绍了如何将 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 转换为带小数秒的日历日期时间字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)