seg.server.fault seg.server.fault - 8 months ago 46
C Question

how to get date and time value in C program

I have something like this:

char *current_day, *current_time;
system("date +%F");
system("date +%T");

It prints the current day and time in the stdout, but I want to get this output or assign them to the
variables, so that I can do some processing with those values later on.

current_day ==> current day
current_time ==> current time

The only solution that I can think of now is to direct the output to some file, and then read the file and then assign the values of date and time to
. But I think this is not a good way. Is there any other short and elegant way?


Use time() and localtime() to get the time:

time_t t = time(NULL);
struct tm tm = *localtime(&t);

printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);