m.r226 m.r226 -4 years ago 159
C Question

C string representation of time_t

I need to store time_t as a string in a char array.
There are some other questions about converting time_t to string but they are not helpful to me. i want to store the value of time_t in a string not to convert that to human readable format. Please take a look this question before any answer.

#include <stdio.h>
#include <time.h>

int main()
{
struct tm epoch_date;
time_t Time_Epoch;
strptime("2017 Jan 1 23:59:59", "%Y %b %d %T", &epoch_date);

Time_Epoch = timegm(&epoch_date); // Time_Epoch: 1488268396
return 0;
}


This piece of code returns timestamp as Time_Epoch.

How should i convert that timestamp to string to give desired output as follows:

The Desired output:
Current date and time are: 1488268396

Answer Source

If the aim is to store the value of time_t in a char array, you can use sprintf as:

char strTime[50];
sprintf(strTime,"%d",Time_Epoch);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download