使用std :: chrono将32位unix时间戳转换为std :: string [英] Convert 32 bit unix timestamp to std::string using std::chrono
问题描述
我正在尝试使用 std :: chrono
创建一个 std :: string
,但是遇到了问题.
I am trying to use std::chrono
to make a std::string
but running into issues.
这是我想模仿的C(-ish)代码:
Here is the C(-ish) code I want to mimick:
std::uint32_t time_date_stamp = 1484693089;
char date[100];
struct tm *t = gmtime(reinterpret_cast<const time_t*>(&time_date_stamp));
strftime(date, sizeof(date), "%Y-%m-%d %I:%M:%S %p", t);
我的起点始终是这个 std :: uint32_t
,它来自我无法控制的数据格式.
My starting point is always this std::uint32_t
, it is from a data format I do not control.
对不起,我没有任何C ++作为起点,我什至不知道如何正确地创建 std :: chrono :: time_point
.
Sorry I do not have any C++ as a starting point, I do not even know how to make a std::chrono::time_point
correctly.
推荐答案
< chrono>
不是用于将日期时间格式化为字符串的库.对于转换不同的时间表示形式(毫秒到天等),将时间戳加在一起等很有用.
<chrono>
is not a library for formatting datetimes into strings. It is useful for converting different time representations (milliseconds to days, etc), adding timestamps together and such.
标准库中唯一的日期时间格式化功能是从C标准库继承的功能,包括您已经在"C(-ish)"版本中使用的 std :: strftime
.正如jaggedSpire所指出的那样,C ++ 11引入了 std :: put_time
.它提供了一种便捷的方式,可以使用与C函数所使用的API相同的API来流式传输格式化日期.
The only datetime formatting functions in the standard library are the ones inherited from the C standard library, including the std::strftime
which you already used in the "C(-ish)" version. As pointed out by jaggedSpire, C++11 introduced std::put_time
. It provides a convenient way to stream formatted dates with the same API as used by the C functions.
由于 std :: gmtime
(如果要使用,请使用 std :: localtime
)将其参数作为Unix时间戳记,因此不需要< chrono>
来转换时间.它已经具有正确的表示形式.只有基础类型必须从 std :: uint32_t
转换为 std :: time_t
.在您的C版本中未实现该功能.
Since std::gmtime
(and std::localtime
if you were to use that) take their argument as a unix timestamp, you don't need <chrono>
to convert the time. It is already in the correct representation. Only the underlying type must be converted from std::uint32_t
to std::time_t
. That is not implemented portably in your C version.
一种可移植的时间戳转换方法,采用基于 std :: put_time
的格式:
A portable way to convert the timestamp, with std::put_time
based formatting:
std::uint32_t time_date_stamp = 1484693089;
std::time_t temp = time_date_stamp;
std::tm* t = std::gmtime(&temp);
std::stringstream ss; // or if you're going to print, just input directly into the output stream
ss << std::put_time(t, "%Y-%m-%d %I:%M:%S %p");
std::string output = ss.str();
这篇关于使用std :: chrono将32位unix时间戳转换为std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!