Oavatog
Oavatog

Reputation: 59

C++ Epoch to Timestamp

Essentially I am looping through a sqlite table getting the relevant data that I need to present, including that of a timestamp which is stored in Epoch like so '1409827517628'. All I wish to do is convert that integer into a string with the format of '"%Y-%m-%d %H:%M:%S'.

Many Thanks.

Upvotes: 0

Views: 2424

Answers (1)

You could use the C functions localtime(3) to convert a time_t (which generally is some integral type) to a struct tm then use strftime(3) to convert it to a C string, e.g.:

time_t yourtime = something(); // from database perhaps
char yourbuf[64];
strftime(yourbuf, sizeof(yourbuf), 
         "%Y-%m-%d %H:%M:%S",
         localtime(&yourtime));
std::string yourstring(yourbuf);

Beware, code above is not re-entrant so not suitable for multi-threaded applications (in that case, use localtime_r etc...)

If you need the opposite conversion (from a string to a time_t), use strptime(3) then mktime(3) ....

With C++11, use also chrono

Upvotes: 2

Related Questions