C mktime()

The mktime() function is defined in the time.h header file. According to the local time zone, it helps to convert the structure pointed to by timeptr into a time_t value.


time_t mktime(struct tm *timeptr); #where timeptr should be a pointer

 

mktime() Parameters: 

The mktime() function takes a single parameter 'timeptr' which is a pointer to the structure which contains a calendar time.The components of calendar time are,


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             */
};

Parameter Description Required / Optional
timeptr the pointer to a time_t value representing a calendar time Required

mktime() Return Value

The function returns time_t value corresponding to the calendar time passed as argument.

Input Return Value
if parameter  time_t value
On failure -1

 

Examples of mktime()

Example 1: Working of mktime() function in C?




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

int main()
{
   int out;
   struct tm info;
   char buf[80];

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

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

   return(0);

}

Output:


Wed Jul 4 00:00:01 2001

Example 2: How asctime() works in C?


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

int main (){

  struct tm t_info;
  time_t t_format;

  t_info.tm_year = 2008-1900;         t_info.tm_m
  t_info.tm_mday = 1;
  t_info.tm_hour = 0;
  t_info.tm_min = 0;
  t_info.tm_sec = 1;
  t_info.tm_isdst = 0;

  t_format = mktime(&t_info);
  printf(ctime(&t_format));
  return 0;
}

Output:


Tue Jan  1 00:00:01 2008