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 假设:
这将使您的时间保持在标准认可的格式中:
需要 #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?