How to get current time in C using gettime()?

Jose G. picture Jose G. · Aug 28, 2017 · Viewed 13.8k times · Source

We're required to use gettime() to get the current time in C. I'm trying to print the current time but the error:

error: storage size of 't' isn't known

occurs. I don't know how to solve this. Here is the code:

#include<stdio.h>
#include<dos.h>

int main(){

   struct time t;

   gettime(&t);

   printf("%d:%d:%d", t.ti_hour,t.ti_min,t.ti_sec);

   getch();
   return 0;
}

Answer

dash-o picture dash-o · Nov 20, 2019

It's not clear if you want to get the time, or just print it.

For the second case, there are few legacy methods that will provide formatted time (asctime, ctime). But those may not fit your needs.

The more flexible option is to use strftime based on data from time/localtime_r. The strftime support many of the escapes (%Y, ...) that are available with GNU date.

#include <stdio.h>
#include <time.h>

void main(void)
{

   time_t now = time(NULL) ;
   struct tm tm_now ;
   localtime_r(&now, &tm_now) ;
   char buff[100] ;
   strftime(buff, sizeof(buff), "%Y-%m-%d, time is %H:%M", &tm_now) ;
   printf("Time is '%s'\n", buff) ;
}