【问题标题】:Convert string time to UNIX timestamp将字符串时间转换为 UNIX 时间戳
【发布时间】:2013-07-16 15:58:39
【问题描述】:

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

我可以从字符串中获取日期部分,但我不知道如何计算秒数。我尝试查看documentation of date and time utilities in C++,但没有找到任何东西。

【问题讨论】:

  • 你有没有尝试过?
  • @Rapptz 查看更新。我尝试查看文档,但没有找到任何内容。
  • C++ 没有像 C# 等其他语言那样好的日期/时间实用程序。您最好的选择可能是在Boost libraries 中找到适合您情况的内容。
  • 无论您是在 Windows 还是 Linux 上,提到两者的解决方案(包括 boost)的答案是 stackoverflow.com/questions/321849/…

标签: c++ unix-timestamp


【解决方案1】:

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

【讨论】:

  • 但这不会返回 UNIX 时间戳。
  • 请考虑让您的答案更全面,例如解释 std::locale、方面以及 mktime 是否领导时区等等。
【解决方案2】:

这是工作代码

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

【讨论】:

    【解决方案3】:

    看看strptime()。有关 Windows 替代方案,请参阅this question

    【讨论】:

    • 特别是如果你不能使用 C++11(可以使用 Iwan Aucamp 的解决方案)
    【解决方案4】:

    您可以使用boost date_time 或更具体的ptime

    使用ptime time_from_string(std::string) 初始化您的时间,使用long total_seconds() 获取持续时间的秒数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 2019-07-30
      • 2019-10-29
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      相关资源
      最近更新 更多