Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the date and time values in a C program?

Tags:

c

datetime

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 current_day and current_time 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 current_day and current_time. But I think this is not a good way. Is there any other short and elegant way?

like image 931
seg.server.fault Avatar asked Sep 18 '09 00:09

seg.server.fault


People also ask

How do I print the time in printf?

printf("The time is: %02d:%02d:%02d\n", ptm->tm_hour, ptm->tm_min, ptm->tm_sec); We use the tm_hour , tm_min , and tm_sec members to express a human-readable time format.

How will you print the date in below format using C?

Print Date/Time with Default Format. Print Date in DD-MM-YYYY Format. Print Time in HH:MM:SS Format. Print Date/Time with Month Name and AM/PM Format.

What type of value is returned by the time () function in C?

Return Value: This function returns current calendar time as a object of type time_t.


1 Answers

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

#include <stdio.h> #include <time.h>  int main() {   time_t t = time(NULL);   struct tm tm = *localtime(&t);   printf("now: %d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); } 
like image 118
Adam Rosenfield Avatar answered Oct 06 '22 00:10

Adam Rosenfield