C library - mktime() function



The C library mktime() function is used to change the time. It converts the time structure into a calender time value. This function accepts the individual components of a date and time such as year, month, day, hour, minutes, and second and calculate the corresponding timestamp.

Here, time_t mktime(struct tm *timeptr) converts the structure pointed to by timeptr into a time_t value according to the local time zone.

Syntax

Following is the syntax of the C library mktime() function −

time_t mktime(struct tm *timeptr)

Parameters

This function accepts only a single parameter −

  • timeptr − This is the pointer to a time_t value representing a calendar time, broken down into its components.
  • Below is the detail of timeptr structure −
struct tm {
   int tm_sec;         /* seconds,  range 0 to 59          */
   int tm_min;         /* minutes, range 0 to 59           */
   int tm_hour;        /* hours, range 0 to 23             */
   int tm_mday;        /* day of the month, range 1 to 31  */
   int tm_mon;         /* month, range 0 to 11             */
   int tm_year;        /* The number of years since 1900   */
   int tm_wday;        /* day of the week, range 0 to 6    */
   int tm_yday;        /* day in the year, range 0 to 365  */
   int tm_isdst;       /* daylight saving time             */	
};

Return Value

This function returns a time_t value corresponding to the calendar time passed as a parameter. The error has occured when it returns -1.

Example 1

Following is the basic C library program to see to demonstration of mktime() function.

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

int main () {
   int ret;
   struct tm info;
   char buffer[80];

   info.tm_year = 2001 - 1900;
   info.tm_mon = 7 - 1;
   info.tm_mday = 4;
   info.tm_hour = 0;
   info.tm_min = 0;
   info.tm_sec = 1;
   info.tm_isdst = -1;

   ret = mktime(&info);
   if( ret == -1 ) {
      printf("Error: unable to make time using mktime\n");
   } else {
      strftime(buffer, sizeof(buffer), "%c", &info );
      printf(buffer);
   }
 
   return(0);
} 

Output

After executing of above code, we get the following result −

Wed Jul 4 00:00:01 2001

Example 2

In this program, we calculates the date and time(100 days and 30 hours) from the present moment and prints the corresponding day of the week.

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

char *weekday[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

int main(void) {
   time_t dt1, dt3;
   struct tm *t2;

   dt1 = time(NULL);
   t2 = localtime(&dt1);

   // Add 100 days and 30 hours
   t2->tm_mday += 100;
   t2->tm_hour += 30;

   dt3 = mktime(t2);

   printf("It will be a %s after 100 days and 30 hours from now.\n", weekday[t2->tm_wday]);
   return 0;
}

Output

The above produces code the following result −

It will be a Saturday after 100 days and 30 hours from now.
Advertisements