[英]How to convert std::chrono::time_point to string
如何将std::chrono::time_point
转换为字符串? 例如: "201601161125"
。
霍华德·辛南特(Howard Hinnant)的免费,开放源代码,仅标头的可移植日期/时间库是一种实现此目的的现代方法,它不会通过旧的C API进行交易,也不需要您丢弃所有亚秒级信息。 该库也正在提议进行标准化 。
格式化具有很大的灵活性。 最简单的方法是流式输出:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
std::cout << std::chrono::system_clock::now() << '\n';
}
这只是为我输出:
2017-09-15 13:11:34.356648
using namespace date;
为了找到system_clock::time_point
的流运算符是必需的(我的lib将其插入namespace std::chrono
system_clock::time_point
是非法的)。 此格式不会丢失任何信息:将输出system_clock::time_point
的完整精度(我在macOS上运行它的microseconds
)。
全套类似于strftime
的格式设置标志可用于其他格式,并进行较小的扩展以处理小数秒之类的内容。 这是另一个以毫秒为单位输出的示例:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << format("%D %T %Z\n", floor<milliseconds>(system_clock::now()));
}
只是为我输出:
09/15/17 13:17:40.466 UTC
最灵活的方法是将其转换为struct tm
,然后使用strftime
(时间类似于sprintf
)。 就像是:
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
的文档。
如果您有localtime_s
或localtime_r
可用,则应优先使用localtime
。
还有许多其他方法可以执行此操作,但是虽然大多数情况下更易于使用,但它们会产生一些预定义的字符串表示形式。 您可以将以上所有内容“隐藏”在一个函数中,以易于使用。
从下面的函数转换chrono
time_point
串(序列化)。
#include <chrono>
#include <iomanip>
#include <sstream>
using time_point = std::chrono::system_clock::time_point;
std::string serializeTimePoint( const time_point& time, const std::string& format)
{
std::time_t tt = std::chrono::system_clock::to_time_t(time);
std::tm tm = *std::gmtime(&tt); //GMT (UTC)
//std::tm tm = *std::localtime(&tt); //Locale time-zone, usually UTC by default.
std::stringstream ss;
ss << std::put_time( &tm, format.c_str() );
return ss.str();
}
// example
int main()
{
time_point input = std::chrono::system_clock::now();
std::cout << serializeTimePoint(input, "UTC: %Y-%m-%d %H:%M:%S") << std::endl;
}
time_point
数据类型没有时区的内部表示,因此,时区通过转换为std::tm
(通过函数gmtime
或localtime
)进行聚合。 不建议从输入中添加/减去时区,因为使用%Z
会显示不正确的时区,因此,最好设置正确的本地时间(取决于OS)并使用localtime()
。
对于技术用途,硬编码的时间格式是一个很好的解决方案。 但是,要向用户显示,应使用locale
来检索用户首选项,并以该格式显示时间戳。
从C ++ 20开始,我们对time_point和duration具有很好的序列化和解析功能。
std::chrono::to_stream
std::chrono::format
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.