如何在 C++11 中将 unix 时间戳字符串正确转换为 time_t?

How to properly convert a unix timestamp string to time_t in C++11?

假设我们有一个文本文件并从那里读取一些时间戳到局部变量 "sTime":

std::string sTime = "1440966379" // this value has been read from a file.
std::time_t tTime = ? // this instance of std::time_t shall be assigned the above value.

如何将此字符串正确转换为 std::time 假设:

  1. 我们可能只使用 STL 方法(没有提升)。
  2. 我们使用 C++11 标准
  3. 我们不知道我们正在使用哪个 CPU architecture/OS(它应该可以跨平台工作)
  4. 我们无法对 time_t 的内部定义方式做出任何(静态)假设。当然我们知道在大多数情况下它将是一个整数类型,可能是 32 或 64 位长度,但是根据 cppreference.com time_t 的实际类型定义没有指定。所以 atoi、atol、atoll、strtoul ... 等至少在我们通过其他方式确保我们确实从这些可能的候选者中选择了正确的人之前是没有问题的。

这将使您的时间保持标准认可的格式:

需要#include <chrono>

std::string sTime = "1440966379"; // this value has been read from a file.

std::chrono::system_clock::time_point newtime(std::chrono::seconds(std::stoll(sTime)));
// this gets you out to a minimum of 35 bits. That leaves fixing the overflow in the 
// capable hands of Misters Spock and Scott. Trust me. They've had worse.

从那里你可以在 time_points.

上进行算术和比较

将其转储到 POSIX 时间戳:

const std::chrono::system_clock::time_point epoch = std::chrono::system_clock::from_time_t(0);
// 0 is the same in both 32 and 64 bit time_t, so there is no possibility of overflow here
auto delta = newtime - epoch;
std::cout << std::chrono::duration_cast<std::chrono::seconds>(delta).count();

另一个 SO 问题涉及恢复格式化字符串: How to convert std::chrono::time_point to std::tm without using time_t?