mktime() 函数在 time.h 头文件中定义。根据当地时区,它有助于将 timeptr 指向的结构转换为 time_t 值。
time_t mktime(struct tm *timeptr); #where timeptr should be a pointer
mktime() 函数接受一个参数 'timeptr',它是一个指向包含日历时间的结构的指针。日历时间的组成部分是:
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 */
};
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| timeptr | 指向表示日历时间的 time_t 值的指针 | 必需 |
该函数返回与作为参数传递的日历时间相对应的 time_t 值。
| 输入 | 返回值 |
|---|---|
| 如果参数 | time_t 值 |
| 失败时 | -1 |
#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);
}
输出
Wed Jul 4 00:00:01 2001
#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;
}
输出
Tue Jan 1 00:00:01 2008