如何将 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 转换为带小数秒的日历日期时间字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)