如何转换std :: chrono :: time_point到日历datetime字符串与小数秒? [英] How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

查看:3434
本文介绍了如何转换std :: chrono :: time_point到日历datetime字符串与小数秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将std :: chrono :: time_point转换为带分数秒的日历datetime字符串?
例如:10-10-2012 12:38:40.123456。

How to convert std::chrono::time_point to calendar datetime string with fractional seconds? For example: "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()函数。此函数从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到日历datetime字符串与小数秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆