Learn C - C Date and Time Functions






The time.h header declares functions that produce the time and date.

Getting Time Values

The simplest function returning a time value has the following prototype:

clock_t clock(void);

This function returns the processor time since some reference point.

You call the clock() function at the start and end of some process in a program.

The return value is of type clock_t, which is an integer type that is defined in time.h.

The value that is returned by the clock() function is measured in clock ticks.

To convert this value to seconds, you divide it by the value that is produced by the macro CLOCKS_PER_SEC, which is defined in time.h.

The clock() function returns -1 if an error occurs.

The time() function returns the calendar time as a value of type time_t.

The calendar time is the current time usually measured in seconds since a fixed time on a particular date.

The fixed time and date is often 00:00:00 GMT on January 1, 1970, and this is typical of how time values are defined.

The prototype of the time() function is:

time_t time(time_t *timer);

If the argument isn't NULL, the current calendar time is also stored in timer.

The type time_t is defined in the header file and is often equivalent to type long.

To calculate the elapsed time in seconds between two successive time_t values returned by time(), you can use the function difftime(), which has this prototype:

double difftime(time_t T2, time_t T1);

The function will return the value of T2 - T1 expressed in seconds as a value of type double.

This value is the time elapsed between the two time() function calls that produce the time_t values, T1 and T2.





Example


#include <stdio.h> 
#include <time.h> 
#include <math.h> 
#include <ctype.h> 
/*from   www  .ja v a 2  s . c o m*/
int main(void) { 
  time_t calendar_start = time(NULL);         // Initial calendar time 
  clock_t cpu_start = clock();                // Initial processor time 
  int count = 0;                              // Count of number of loops 
  const long long iterations = 1000000000LL;  // Loop iterations 
  char answer = 'y'; 
  double x = 0.0; 
  printf("Initial clock time = %lld Initial calendar time = %lld\n", 
            (long long)cpu_start, (long long)calendar_start); 
  while(tolower(answer) == 'y') { 
    for(long long i = 0LL ; i < iterations ; ++i) 
      x = sqrt(3.14159265); 
  
    printf("%lld square roots completed.\n", iterations*(++count)); 
    printf("Do you want to run some more(y or n)? \n"); 
    scanf("\n%c", &answer, sizeof(answer)); 
  } 
  
  clock_t cpu_end = clock();                  // Final cpu time 
  time_t calendar_end = time(NULL);           // Final calendar time 
  
  printf("Final clock time = %lld Final calendar time = %lld\n", 
     (long long)cpu_end, (long long)calendar_end); 
  printf("CPU time for %lld iterations is %.2lf seconds\n", 
     count*iterations, ((double)(cpu_end-cpu_start))/CLOCKS_PER_SEC); 
  printf("Elapsed calendar time to execute the program is %8.2lf seconds.\n", 
     difftime(calendar_end, calendar_start)); 
  return 0; 
} 

The code above generates the following result.





Getting the Date

To get today's date as a string, use the function ctime(), which has this prototype:

char *ctime(const time_t *timer);

The function accepts a pointer to a time_t variable as an argument that contains a calendar time value returned by the time() function.

It returns a pointer to a 26-character string containing the day, the date, the time, and the year, which is terminated by a newline and '\0'.

A typical string returned might be the following:

"Mon Aug 21 11:45:56 2015\n\0" 

The ctime() function has no knowledge of the string length allocated to store the result.

There is an optional safer version of the function that has this prototype:

errno_t ctime_s(char * str, rsize_t size, const time_t *timer);

You might use the ctime_s() function like this:

char time_str[30] = {'\0'}; 
time_t calendar = time(NULL); 
if(!ctime_s(time_str, sizeof(time_str), &calendar)) 
   printf_s("%s", time_str); 
else 
   fprintf_s(stderr, "Error converting time_t value\n"); 
   

We can get at the various components of the time and date from a calendar time value by using the localtime() function. This has the prototype:

struct tm *localtime(const time_t *timer);

This function accepts a pointer to a time_t value and returns a pointer to a structure of type tm, which is defined in time.h.

It returns NULL if timer cannot be converted.

The optional version has the prototype:

struct tm *localtime_s(const time_t * restrict timer, 
                            struct tm * restrict result); 

Both arguments must be non_NULL.

The structure contains at least the members listed in the following Table.

MemberDescription
tm_secSeconds (0 to 60) after the minute on 24-hour clock. This value goes up to 60 for positive leap-second support.
tm_minMinutes after the hour on 24-hour clock (0 to 59)
tm_hourThe hour on 24-hour clock (0 to 23)
tm_mdayDay of the month (1 to 31)
tm_monMonth (0 to 11)
tm_yearYear (current year minus 1900)
tm_wdayWeekday (Sunday is 0; Saturday is 6)
tm_ydayDay of year (0 to 365)
tm_isdstDaylight saving flag. Positive for daylight saving time, 0 for not daylight saving time, negative for not known.

All the members are of type int.

Here's a code fragment that will output the day and the date from the members of the tm structure:

time_t calendar = time(NULL);                 // Current calendar time 
struct tm time_data; 
const char *days[] =   {"Sunday",   "Monday", "Tuesday", "Wednesday", 
                        "Thursday", "Friday", "Saturday"              }; 
const char *months[] = {"January", "February", "March", 
                        "April",    "May",     "June", 
                        "July",    "August",   "September", 
                        "October", "November", "December"  }; 

if(localtime_s(&calendar, &time_data)) 
  printf_s("Today is %s %s %d %d\n", 
                    days[time_data.tm_wday], months[time_data.tm_mon], 
                    time_data.tm_mday,       time_data.tm_year+1900); 

The asctime() and its optional safer partner asctime_s() generate a string representation of a tm structure.

Their prototypes are:

  
char *asctime(const struct tm *time_data); 
errno_t asctime_s(char *str, rsize_t size, const struct tm *time_data); 

The asctime_s() stores the string in str, which must be an array with at least 26 elements; size is the number of elements in str.

The function returns 0 on success and a nonzero integer when failure.

The function works for tm structures where the year is from 1000 to 9999.

The string that results is of the same form as that produced by ctime().


#include <stdio.h> 
#include <time.h> 
  // ww  w . jav  a2 s  . c om
int main(void) 
{ 
  const char *day[7] = { 
                   "Sunday"  , "Monday", "Tuesday", "Wednesday", 
                   "Thursday", "Friday", "Saturday" 
                       }; 
  const char *month[12] = { 
                     "January",   "February", "March",    "April", 
                     "May",       "June",     "July",     "August", 
                     "September", "October",  "November", "December" 
                          }; 
  const char *suffix[] = { "st", "nd", "rd", "th" }; 
  enum sufindex { st, nd, rd, th } sufsel = th;       // Suffix selector 
  
  struct tm ourT;                                     // The time structure 
  time_t tVal = time(NULL);                           // Calendar time 
  
  if(!localtime_s(&tVal, &ourT))                      // Populate time structure 
  { 
    fprintf(stderr, "Failed to populate tm struct.\n"); 
    return -1; 
  } 
  switch(ourT.tm_mday) 
  { 
    case 1: case 21: case 31: 
      sufsel= st; 
      break; 
    case 2: case 22: 
      sufsel= nd; 
      break; 
    case 3: case 23: 
      sufsel= rd; 
      break; 
    default: 
      sufsel= th; 
      break; 
  } 
  
  printf("Today is %s the %d%s %s %d. ", 
      day[ourT.tm_wday], 
      ourT.tm_mday, 
      suffix[sufsel], 
      month[ourT.tm_mon], 
      1900 + ourT.tm_year); 
  printf("The time is %d : %d : %d.\n", 
      ourT.tm_hour, ourT.tm_min, ourT.tm_sec ); 
  return 0; 
}

The code above generates the following result.

Getting the Day for a Date

You can use the mktime() function to determine the day of the week for a given date.

The function has the prototype:

time_t mktime(struct tm *ptime);

#include <stdio.h> 
#include <time.h> 
  /* w w  w. j ava2  s . co  m*/
int main(void) 
{ 
  const char *day[7] = { 
                   "Sunday"  , "Monday", "Tuesday", "Wednesday", 
                   "Thursday", "Friday", "Saturday" 
                       }; 
  const char *month[12] = { 
                     "January",   "February", "March",    "April", 
                     "May",       "June",     "July",     "August", 
                     "September", "October",  "November", "December" 
                          }; 
  const char *suffix[] = { "st", "nd", "rd", "th" }; 
  enum sufindex { st, nd, rd, th } sufsel = th;  // Suffix selector 
  
  struct tm birthday = {0};                      // A birthday time structure 
  char name[30] = {"C"}; 
  
  printf("Enter the birthday as day month year integers separated by spaces." 
             "\ne.g. Enter 1st February 1985 as 1 2 1985 : "); 
  scanf(" %d %d %d", &birthday.tm_mday, &birthday.tm_mon, &birthday.tm_year); 
  
  birthday.tm_mon -= 1;                          // Month zero-based 
  birthday.tm_year -= 1900;                      // Year relative to 1900 
  
  if(mktime(&birthday) == - 1) 
  { 
    fprintf_s(stderr, "Operation failed.\n"); 
    return -1; 
  } 
  
  switch(birthday.tm_mday) 
  { 
    case 1: case 21: case 31: 
      sufsel= st; 
      break; 
    case 2: case 22: 
      sufsel= nd; 
      break; 
    case 3: case 23: 
      sufsel= rd; 
      break; 
    default: 
      sufsel= th; 
      break; 
  } 
  printf("born on the %d%s %s %d, which was a %s.\n", 
                 birthday.tm_mday, suffix[sufsel], month[birthday.tm_mon], 
                            1900 + birthday.tm_year, day[birthday.tm_wday]); 
  return 0; 
} 

The code above generates the following result.