7

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

user63898
  • 28,093
  • 80
  • 242
  • 473

1 Answers1

10

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)
ormurin
  • 358
  • 3
  • 11