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