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

nor*_*itt 4 c++ string time type-conversion

假设我们有一个文本文件,并将一些时间戳从那里读取到局部变量“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.
Run Code Online (Sandbox Code Playgroud)

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

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

use*_*301 5

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

需要 #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.
Run Code Online (Sandbox Code Playgroud)

从那里你可以做算术和比较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();
Run Code Online (Sandbox Code Playgroud)

另一个 SO 问题是处理格式化字符串: How to convert std::chrono::time_point to std::tm without using time_t?