How do I convert a Unix timestamp string to time_t in C++11?

acidrums4 picture acidrums4 · May 29, 2016 · Viewed 7.3k times · Source

Short question, aka "TD;DR".

I have a, say, "1464478647000" string, that I guess is a UNIX timestamp. But surely it is a string containing a number that represents time, but not in a human readable format. How do I convert it to a time_t type so I can format it later to a formated string, like "3 minutes ago" in C++11?


Long question.

Sorry for my bad english, first of all.

I'm totally noob at C++11, and even C++; I just learnt a little of C and that was like 10 years ago, I almost forgot how it was. On my spare time, I'm trying to do a little fork of Feednix (a ncurses program, written in C++11, that acts as a Feedly client for Linux console - and looks like it's dead) so it looks more like a list (kind of how ncmpcpp or mutt look like). As the current Feednix implementation is not showing time of any post, I thought it would be nice to make it show the time it was published (as the web version of Feedly does, on its "Titles only" presentation).

The thing is that following the model of what's implemented on Feednix, I'm pulling the 'published' data as a string object (I couldn't figure how to pull it as an integer, or directly as a time_t object (seems the Json library doesn't allow to do that). Said 'published' data, says Feedly API docs, is "the timestamp, in ms, when this article was published, as reported by the RSS feed (often inaccurate)." An example of that is "1452614967000".

So how can I do to convert that string to a time_t object, so I can later format it to a string like "3 minutes ago" or "2 days ago"? Or is anything better I can do to get that formatted string (which is more likely)? Any help would be appreciated!

Answer

Jerfov2 picture Jerfov2 · May 29, 2016

First, convert the number into long using strtol, then cast to time_t:

#include <cstdlib>
#include <ctime>

using namespace std; // to simplify answer

...
const char* timestr = "1464478647000";
time_t timenum = (time_t) strtol(timestr, NULL, 10);