Get the current time in C

Antrromet picture Antrromet · Feb 28, 2011 · Viewed 480.2k times · Source

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.

Answer

mingos picture mingos · Feb 28, 2011

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)