Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly convert a unix timestamp string to time_t in C++11?

Lets say we have a text file and read some timestamp from there into a local variable "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.

How do I convert this string properly into std::time assuming:

  1. We may use STL means only (no boost).
  2. We use the C++11 standard
  3. We don't know which CPU architecture/OS we're using (it should work cross plattform)
  4. We can not make any (static) assumptions on how time_t is internally defined. Of course we know that in most cases it will be an integral type, probably of 32 or 64 bit length, but according to cppreference.com the actual typedef of time_t is not specified. So atoi, atol, atoll, strtoul ... etc. are out of question at least until we have made sure by other means that we actually did pick the correct one out of those possible candidates.
like image 827
norritt Avatar asked Aug 30 '15 20:08

norritt


People also ask

What is Time_t C++?

The time_t type is an arithmetic type that represents a date and time. The actual type and the encoding of the date and time are implementation-defined.

What is Unix timestamp string?

The Unix timestamp is the number of seconds calculated since January 1, 1970.

How do I convert UNIX time to normal time in Excel?

For converting 11 digits timestamp to a standard datetime, use the formula as this:=A1/864000+DATE(1970,1,1), A1 is the cell that contains the 11-digits you want to convert to.


1 Answers

This will keep your time in a standards-approved format:

Need #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.

From there you can do arithmetic and compares on time_points.

Dumping it back out to a POSIX timestamp:

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();

And another SO question deals with getting formatted strings back out: How to convert std::chrono::time_point to std::tm without using time_t?

like image 114
user4581301 Avatar answered Sep 21 '22 03:09

user4581301