C Library Function - mktime()
Description
The C library function time_t mktime(struct tm *timeptr) converts the structure pointed to by timeptr into the number of seconds elapsed since January 1, 1970. It returns -1 if an error occurs.
Declaration
Below is the declaration for the mktime() function.
time_t mktime(struct tm *timeptr)
Parameters
- timeptr -- This is a pointer to a tm structure representing a calendar time broken down into its components. Below are the details of the 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; /* Year 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
The function returns the number of seconds elapsed since January 1, 1970. If an error occurs, it returns -1.
Example
The following example demonstrates the use of the mktime() function.
#include <stdio.h>
#include <time.h>
int main () {
int ret;
struct tm info;
char buffer[80];
info.tm_year = 2021 - 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);
}
Let's compile and run the above program, which will produce the following result:
Sun Jul 4 00:00:01 2021
Example
/* Determine the day of the week for a given date */
#include <stdio.h> /* printf, scanf */
#include <time.h> /* time_t, struct tm, time, mktime */
int main ()
{
time_t rawtime;
struct tm * timeinfo;
int year, month ,day;
const char * weekday[] = { "Sunday", "Monday","Tuesday", "Wednesday","Thursday", "Friday", "Saturday"};
/* User inputs the date */
printf ("Year: "); fflush(stdout); scanf ("%d",&year);
printf ("Month: "); fflush(stdout); scanf ("%d",&month);
printf ("Day: "); fflush(stdout); scanf ("%d",&day);
/* Get current time information and modify it with the input date */
time(&rawtime);
timeinfo = localtime(&rawtime);
timeinfo->tm_year = year - 1900;
timeinfo->tm_mon = month - 1;
timeinfo->tm_mday = day;
/* Call mktime: timeinfo->tm_wday */
mktime(timeinfo);
printf("That day was: %s\n", weekday[timeinfo->tm_wday]);
return 0;
}
Let's compile and run the above program, which will produce the following result:
Year: 2018
Month: 7
Day: 26
That day was: Thursday