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:

  1. we may use stl means (no boost).
  2. we use c++11 standard
  3. we don't know cpu architecture/os we're using (it should work cross plattform)
  4. 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

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -