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

标签 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 的实际类型定义。所以 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?

关于c++ - 如何在 C++11 中将 unix 时间戳字符串正确转换为 time_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32300972/

相关文章:

计算字符串数组中的字符数?

c++ - 有人可以解释以下语法及其功能吗?

windows - 通过cmd文件在csv文件末尾追加时间

mysql - 如何将时间四舍五入到最接近的 15 分钟段

c++ - 比较位(一次一个位置)

c++ - 如何在不生成大量测试客户端应用程序的情况下切换元素和容器类型以进行基准测试?

c++ - NULL != C++ 中的值是什么意思?

c - 初始化指向字符串 : garbled text? 的指针

Mysql,按时间间隔获取不同值计数

c++ - 如何让代码完成在 Sublime Text 3 中为 c++ 工作?