Get the current time in C
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.
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;
}
To extend the answer from @mingos above, I wrote the below function to format my time to a specific format ([dd mm yyyy hh:mm:ss]).
// Store the formatted string of time in the output
void format_time(char *output){
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
sprintf(output, "[%d %d %d %d:%d:%d]", timeinfo->tm_mday,
timeinfo->tm_mon + 1, timeinfo->tm_year + 1900,
timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
}
More information about struct tm
can be found here.
#include<stdio.h>
#include<time.h>
void main()
{
time_t t;
time(&t);
printf("\n current time is : %s",ctime(&t));
}