Get the current time in C

2019-01-06 10:22发布

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.

8条回答
虎瘦雄心在
2楼-- · 2019-01-06 11:18

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)

查看更多
走好不送
3楼-- · 2019-01-06 11:18

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.

查看更多
登录 后发表回答