Thursday, April 21, 2011

Getting a unix timestamp as a string in C++

I'm using the function time() in order to get a timestamp in C++, but, after doing so, I need to convert it to a string. I can't use ctime, as I need the timestamp itself (in its 10 character format). Trouble is, I have no idea what form a time_t variable takes, so I don't know what I'm converting it from. cout handles it, so it must be a string of some description, but I have no idea what.

If anyone could help me with this it'd be much appreciated, I'm completely stumped.

Alternately, can you provide the output of ctime to a MySQL datetime field and have it interpreted correctly? I'd still appreciate an answer to the first part of my question for understanding's sake, but this would solve my problem.

From stackoverflow
  • http://www.codeguru.com/forum/showthread.php?t=231056

    In the end time_t is just an integer.

  • Try sprintf(string_variable, "%d", time) or std::string(itoa(time))?

    wyatt : This allowed the process timestamp to be printed, but it always returns 134515192. specifically, my code is: char timestamp[10]; sprintf(timestamp, "%d", time); then later query += timestamp query being an std::string.
  • time_t is some kind of integer. If cout handles it in the way you want, you can use a stringstream to convert it to a string:

    std::string timestr(time_t t) {
       std::stringstream strm;
       strm << t;
       return strm.str();
    }
    

0 comments:

Post a Comment