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

时间:2015-08-30 20:44:00

标签: 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.

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

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

1 个答案:

答案 0 :(得分:3)

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

需要#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?