加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用std :: chrono将32位unix时间戳转换为std :: string

发布时间:2020-12-16 10:05:09 所属栏目:百科 来源:网络整理
导读:我试图使用std :: chrono来创建一个std :: string但是遇到问题. 这是我想模仿的C(-ish)代码: std::uint32_t time_date_stamp = 1484693089;char date[100];struct tm *t = gmtime(reinterpret_castconst time_t*(time_date_stamp));strftime(date,sizeof(da
我试图使用std :: chrono来创建一个std :: string但是遇到问题.

这是我想模仿的C(-ish)代码:

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,它来自我无法控制的数据格式.

对不起,我没有任何C作为起点,我甚至不知道如何正确制作std :: chrono :: time_point.

解决方法

<计时>不是用于将日期时间格式化为字符串的库.它可用于转换不同的时间表示(毫秒到天等),将时间戳添加到一起等.

标准库中唯一的日期时间格式化函数是从C标准库继承的函数,包括已在“C(-ish)”版本中使用的std :: strftime.编辑:正如jaggedSpire所指出的,C 11引入了std :: put_time.它提供了一种使用与C函数使用的API相同的API来传输格式化日期的便捷方法.

由于std :: gmtime(以及std :: localtime,如果您要使用它)将其参数作为unix时间戳,您不需要< chrono>转换时间.它已经在正确的表示中.只有底层类型必须从std :: uint32_t转换为std :: time_t.这在您的C版本中并未实现.

一种可移植的方式来转换时间戳,使用基于std :: put_time的格式:

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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读