C library functions -mktime()
Description
C Library Functionstime_t mktime(struct tm *timeptr)holdtimeptrConverts the structure pointed to into seconds of duration since January 1, 1970, returning -1 if an error occurs.
Declaration
The following is the declaration of the mktime() function.
time_t mktime(struct tm *timeptr)
Parameter
- timeptr-- This is a pointer to a time_t value representing calendar time, which is broken down into the following parts. Below are the details of the timeptr structure:
struct tm {
int tm_sec; /* 秒,范围从 0 到 59 */
int tm_min; /* 分,范围从 0 到 59 */
int tm_hour; /* 小时,范围从 0 到 23 */
int tm_mday; /* 一月中的第几天,范围从 1 到 31 */
int tm_mon; /* 月份,范围从 0 到 11 */
int tm_year; /* 自 1900 起的年数 */
int tm_wday; /* 一周中的第几天,范围从 0 到 6 */
int tm_yday; /* 一年中的第几天,范围从 0 到 365 */
int tm_isdst; /* 夏令时 */
};
Return Value
This function returns the number of seconds of duration since January 1, 1970. If an error occurs, it returns the value -1.
Example
The following example demonstrates the usage of the mktime() function.
Example
#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);
}
#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 us compile and run the above program, this will produce the following result:
Sun Jul 4 00:00:01 2021
Example
/*Enter a date to determine the day of the week*/
#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 input 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 the user's input information*/
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 is: %s\n", weekday[timeinfo->tm_wday]);
return 0;
}
Let us compile and run the above program, this will produce the following result:
年: 2018 月: 7 日: 26 那一天是:周四other extensions