将字符串时间转换为 UNIX 时间戳

将字符串时间转换为 UNIX 时间戳

问题描述:

我有一个类似 2013-05-29T21:19:48Z 的字符串.我想将它转换为自 1970 年 1 月 1 日(UNIX 纪元)以来的秒数,这样我就可以只使用 4 个字节(或者可能是 5 个字节,以避免 2038 年的问题)来保存它.我怎样才能以便携的方式做到这一点?(我的代码必须同时在 Linux 和 Windows 上运行.)

I have a string like 2013-05-29T21:19:48Z. I'd like to convert it to the number of seconds since 1 January 1970 (the UNIX epoch), so that I can save it using just 4 bytes (or maybe 5 bytes, to avoid the year 2038 problem). How can I do that in a portable way? (My code has to run both on Linux and Windows.)

我可以从字符串中取出日期部分,但我不知道如何计算秒数.我尝试查看 C++ 中日期和时间实用程序的文档,但我没有找到任何东西.

I can get the date parts out of the string, but I don't know how to figure out the number of seconds. I tried looking at the documentation of date and time utilities in C++, but I didn't find anything.

这是工作代码

string s{"2019-08-22T10:55:23.000Z"};
std::tm t{};
std::istringstream ss(s);

ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S");
if (ss.fail()) {
    throw std::runtime_error{"failed to parse time string"};
}   
std::time_t time_stamp = mktime(&t);