Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current time in C

I want to get the current time of my system. For that I'm using the following code in C:

time_t now; struct tm *mytime = localtime(&now);  if ( strftime(buffer, sizeof buffer, "%X", mytime) ) {     printf("time1 = \"%s\"\n", buffer); } 

The problem is that this code is giving some random time. Also, the random time is different everytime. I want the current time of my system.

like image 534
Antrromet Avatar asked Feb 28 '11 12:02

Antrromet


People also ask

What is current time in C?

The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer. The returned string has the following format: Www Mmm dd hh:mm:ss yyyy.

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.

What does time function do in C?

time() function in C The time() function is defined in time. h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.

What is time_t type in C?

The time_t datatype is a data type in the ISO C library defined for storing system time values. Such values are returned from the standard time() library function. This type is a typedef defined in the standard <time.


2 Answers

Copy-pasted from here:

/* localtime example */ #include <stdio.h> #include <time.h>  int main () {   time_t rawtime;   struct tm * timeinfo;    time ( &rawtime );   timeinfo = localtime ( &rawtime );   printf ( "Current local time and date: %s", asctime (timeinfo) );      return 0; } 

(just add void to the main() arguments list in order for this to work in C)

like image 157
mingos Avatar answered Oct 16 '22 10:10

mingos


Initialize your now variable.

time_t now = time(0); // Get the system time 

The localtime function is used to convert the time value in the passed time_t to a struct tm, it doesn't actually retrieve the system time.

like image 38
Erik Avatar answered Oct 16 '22 08:10

Erik