非常教程

C参考手册

日期与时间 | Date and time

mktime

在头文件<time.h>中定义

time_t mktime(struct tm * time);

将表示为struct tm对象的本地日历时间重新规范化,并将其转换为时代以来的时间作为time_t对象。time->tm_wday并被time->tm_yday忽略。中的数值time不检查超出范围。

试图确定夏令时是否在指定时间内生效的time->tm_isdst原因的负值mktime

如果转换time_t成功,time则修改该对象。所有字段都会time更新以适合其适当的范围。time->tm_wdaytime->tm_yday使用其他领域的信息重新计算。

参数

时间

-

指向指定本地日历时间转换的tm对象的指针

返回值

自成立以来的时间作为time_t成功的对象,或者-1如果time不能被表示为time_t对象(在这种情况下POSIX也需要EOVERFLOW被存储errno)。

注释

如果该struct tm对象是从POSIX strptime或等价函数获得的,则其值tm_isdst是不确定的,并且需要在调用之前明确设置mktime

#define _POSIX_C_SOURCE 200112L // for setenv on gcc
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
 
int main(void)
{
    setenv("TZ", "/usr/share/zoneinfo/America/New_York", 1); // POSIX-specific
 
    struct tm tm = *localtime(&(time_t){time(NULL)});
    printf("Today is           %s", asctime(&tm));
    printf("(DST is %s)\n", tm.tm_isdst ? "in effect" : "not in effect");
    tm.tm_mon -= 100;  // tm_mon is now outside its normal range
    mktime(&tm);       // tm_dst is not set to -1; today's DST status is used
    printf("100 months ago was %s", asctime(&tm));
    printf("(DST was %s)\n", tm.tm_isdst ? "in effect" : "not in effect");
}

输出:

Today is           Fri Apr 22 11:53:36 2016
(DST is in effect)
100 months ago was Sat Dec 22 10:53:36 2007
(DST was not in effect)

参考

  • C11标准(ISO / IEC 9899:2011):
    • 7.27.2.3 mktime函数(p:390-391)
  • C99标准(ISO / IEC 9899:1999):
    • 7.23.2.3 mktime函数(p:340-341)
  • C89 / C90标准(ISO / IEC 9899:1990):
    • 4.12.2.3 mktime函数
C

C 语言是一门通用计算机编程语言,应用广泛。C 语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。