gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:38:46 25 4
gpt4 key购买 nike

假设我们有一个文本文件,并从那里读取一些时间戳到局部变量“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com