C Library Function - mktime()
Description
C library function *time_t mktime(struct tm timeptr) Puts the timeptr converts the pointed-to structure into the number of seconds elapsed since January 1, 1970; returns -1 if an error occurs.
Declaration
The following is the declaration of the mktime() function.
time_t mktime(struct tm *timeptr)
Parameters
- timeptr -- This is a pointer to a time_t value representing calendar time, which is broken down into the following parts. The details of the timeptr structure are as follows:
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 elapsed since January 1, 1970. If an error occurs, it returns -1.
Example
The following example demonstrates the use of the mktime() function.
Example
#include
#include
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
/*
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 enters a date
*/
printf
(
"
Year:
"
)
;
fflush
(
stdout
)
;
scanf
(
"
%d
"
,&
year
)
;
printf
(
"
Month:
"
)
;
fflush
(
stdout
)
;
scanf
(
"
%d
"
,&
month
)
;
printf
(
"
Day:
"
)
;
fflush
(
stdout
)
;
scanf
(
"
%d
"
,&
day
)
;
/*
Get the current time information and modify the input entered by the user
*/
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's compile and run the above program, which will produce the following result:
年: 2018
月: 7
日: 26
那一天是:周四
C Standard Library -