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.
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.
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With