1

I have time in Seconds and I want to convert this time in to Readable Time Sting as,
DAY-Date-Hour-Min-Sec-Month-Year.

How to do this in CPP or C.

User7723337
  • 11,857
  • 27
  • 101
  • 182
  • [see this thread](http://stackoverflow.com/questions/1692184/best-way-to-convert-epoch-time-to-real-date-time) – ayush Feb 04 '11 at 11:27
  • `man 3 strftime` or read it [online](http://www.cplusplus.com/reference/clibrary/ctime/strftime/) – Kimvais Feb 04 '11 at 11:27

1 Answers1

4

time(), localtime() and sprintf() should do the trick.

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>.
#endif

#include <time.h>

static const char *Weekdays[] = {
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
     };

int main() {
    time_t curSec;
    struct tm *curDate;
    char dateString[32];

    curSec = time(NULL);
    curDate = localtime(&curSec);
    sprintf(dateString,
        "%s-%02d-%02d-%02d-%02d-%02d-%d",
        Weekdays[curDate->tm_wday],
        curDate->tm_mday,
        curDate->tm_hour,
        curDate->tm_min,
        curDate->tm_sec,
        curDate->tm_mon+1,
        curDate->tm_year+1900);

    printf("%s\n",dateString);
    return 0;
}
v1Axvw
  • 3,054
  • 3
  • 26
  • 40