Get the current time in C
Easy way:
#include <time.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
time_t mytime = time(NULL);
char * time_str = ctime(&mytime);
time_str[strlen(time_str)-1] = '\0';
printf("Current Time : %s\n", time_str);
return 0;
}
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.