[英]Convert 32 bit unix timestamp to std::string using std::chrono
我正在嘗試使用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++11/14 免費、開源、僅頭文件庫,而無需下降到 C 的tm
。
#include "date.h"
#include <iostream>
#include <string>
int
main()
{
std::uint32_t time_date_stamp = 1484693089;
date::sys_seconds tp{std::chrono::seconds{time_date_stamp}};
std::string s = date::format("%Y-%m-%d %I:%M:%S %p", tp);
std::cout << s << '\n';
}
這輸出:
2017-01-17 10:44:49 PM
這沒有與古老的gmtime
C 函數相關的線程安全問題。
date::sys_seconds
上面是一個typedef
為std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>
。
<chrono>
不是用於將日期時間格式化為字符串的庫。 它對於轉換不同的時間表示(毫秒到天等)、將時間戳添加在一起等很有用。
標准庫中唯一的日期時間格式化函數是從 C 標准庫繼承的函數,包括您已經在“C(-ish)”版本中使用的std::strftime
。 編輯:正如 jaggedSpire 所指出的,C++11 引入了std::put_time
。 它提供了一種使用與 C 函數相同的 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.