c++ time stamp to human readable datetime function
29,776
It can be boiled down to:
std::string UT::timeStampToHReadble(const time_t rawtime)
{
struct tm * dt;
char buffer [30];
dt = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%m%d%H%M%y", dt);
return std::string(buffer);
}
Changes:
- I would prefer to do the casting outside the function. It would be weird to cast a time_t to a long before calling the function, if the caller had the time_t data.
- It's not necessary to have two buffers (and therefore not necessary to copy with sprintf)
Comments
-
user63898 over 3 years
i have simple function that i need to return human readable date time from timestamp but somehow it returns the same timestam in seconds:
input 1356953890
std::string UT::timeStampToHReadble(long timestamp) { const time_t rawtime = (const time_t)timestamp; struct tm * dt; char timestr[30]; char buffer [30]; dt = localtime(&rawtime); // use any strftime format spec here strftime(timestr, sizeof(timestr), "%m%d%H%M%y", dt); sprintf(buffer,"%s", timestr); std::string stdBuffer(buffer); return stdBuffer; }
output 1231133812
this is how i call it :
long timestamp = 1356953890L ; std::string hreadble = UT::timeStampToHReadble(timestamp); std::cout << hreadble << std::endl;
and the output is : 1231133812 and i what it to be somekind of this format : 31/1/ 2012 11:38:10 what im missing here ?
UTDATE :
the solution strftime(timestr, sizeof(timestr), " %H:%M:%S %d/%m/%Y", dt); -
Frank Conry about 10 yearsDo you mean
strftime(buffer, sizeof(buffer), "%m%d%H%M%y", dt);
on that second to last line?