如何将std :: chrono :: time_point转换为字符串 [英] How to convert std::chrono::time_point to string

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

问题描述

如何将 std :: chrono :: time_point 转换为字符串?
例如: 201601161125

How to convert std::chrono::time_point to string? For example: "201601161125".

推荐答案

The最灵活的方法是将其转换为 struct tm ,然后使用 strftime (就像 sprintf )。像这样的东西:

The most flexible way to do so is to convert it to struct tm and then use strftime (it's like sprintf for time). Something like:

std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::tm now_tm = *std::localtime(&now_c);
/// now you can format the string as you like with `strftime`

随意设置字符串格式在 strftime 此处

Look up the documentation for strftime here.

如果您有 localtime_s localtime_r 可用,您应该优先使用 localtime

If you have localtime_s or localtime_r available you should use either in preference to localtime.

还有很多其他方法可以执行此操作多数情况下更易于使用,它们导致了一些预定义的字符串表示形式。您可以将上述所有内容隐藏在一个易于使用的函数中。

There are many other ways to do this, but, while mostly easier to use, these result in some predefined string representation. You could just "hide" all of the above in a function for ease of use.

这篇关于如何将std :: chrono :: time_point转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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