c++ - How to properly convert a unix timestamp string to time_t in C++11? -
lets have text file , read timestamp there local variable "stime":
std::string stime = "1440966379" // value has been read file. std::time_t ttime = ? // instance of std::time_t shall assigned above value.
how convert string std::time assuming:
- we may use stl means (no boost).
- we use c++11 standard
- we don't know cpu architecture/os we're using (it should work cross plattform)
- we can not make (static) assumptions on how time_t internally defined. of course know in cases integral type, of 32 or 64 bit length, according cppreference.com actual typedef of time_t not specified. atoi, atol, atoll, strtoul ... etc. out of question @ least until have made sure other means did pick correct 1 out of possible candidates.
this keep time in standards-approved format:
need #include <chrono>
std::string stime = "1440966379"; // value has been read file. std::chrono::system_clock::time_point newtime(std::chrono::seconds(std::stoll(stime))); // gets out minimum of 35 bits. leaves fixing overflow in // capable hands of misters spock , scott. trust me. they've had worse.
from there can arithmetic , compares on time_points
.
dumping out posix timestamp:
const std::chrono::system_clock::time_point epoch = std::chrono::system_clock::from_time_t(0); // 0 same in both 32 , 64 bit time_t, there no possibility of overflow here auto delta = newtime - epoch; std::cout << std::chrono::duration_cast<std::chrono::seconds>(delta).count();
and question deals getting formatted strings out: how convert std::chrono::time_point std::tm without using time_t?
Comments
Post a Comment