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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17681439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:21:12  来源:igfitidea点击:

Convert string time to UNIX timestamp

c++unix-timestamp

提问by svick

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.)

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

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.

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

回答by Iwan Aucamp

use std::get_timeif you want the c++ way - but both other options are also valid. strptime will ignore the Z at the end - and the T can be accomodated by format string %Y-%m-%dT%H:%M:%s- but you could also just put the Z at the end.

如果您想要 c++ 方式,请使用std::get_time- 但其他两个选项也都有效。strptime 将忽略末尾的 Z - 并且 T 可以由格式字符串容纳%Y-%m-%dT%H:%M:%s- 但您也可以将 Z 放在末尾。

回答by Joanna

Here is the working code

这是工作代码

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

回答by freitass

Take a look at strptime(). For a Windows alternative, see this question.

看看strptime()。有关 Windows 替代方案,请参阅此问题

回答by user1810087

You could use boost date_timeore more specific ptime.

您可以使用更具体的boost date_timeptime

Use ptime time_from_string(std::string)to init your time and long total_seconds()to get the seconds of the duration.

使用ptime time_from_string(std::string)来初始化你的时间,并long total_seconds()获得持续的秒。