I have a char holding an epoch time, I am trying to convert this into the date/time format of YYYY/mm/dd/HH:MM:SS,
I have been using strftime but can't seem to get it right,
Can anyone give me a hand?
time_t eventFinish = endTime;
struct tm *tm2 = localtime(&eventFinish);
//syslog( LOG_INFO, "eventFinish:: %s", eventFinish);
char buf2[64];
strftime( buf2, sizeof( buf2 ), "%Y%m%d%H%M%S", &tm2 );
syslog( LOG_INFO, "Your time: %s", buf2 );
eventFinish outputs the epoch time I am expecting, buf2 outputs random numbers.
You have to convert your unix timestamp into a struct tm
first
time_t ts = 1562230784; // current time as example
struct tm *tm = localtime(&ts);
and then use this with strftime()
:
char buf[64];
strftime(buf, sizeof(buf), "%Y/%m/%d/%H:%M:%S", tm);
printf("Your time: %s\n", buf);
The relevant structures are defined in time.h
.
This should about do what you want.
Note that this will return the time in the local timezone configured in your system. To get UTC, you can use gmtime()
instead of localtime()
.