std::mktime

定义于头文件 <ctime>
std::time_t mktime( std::tm* time );

转换本地日历时间为从纪元起的时间,作为 time_t 对象。忽略 time->tm_wdaytime->tm_yday 。容许 time 中的值在其正常范围外。

time->tm_isdst 的负值会导致 mktime 尝试确定在指定时间夏时令是否有效。

若转换到 time_t 成功,则修改 time 会被修改。更新 time 的所有域为符合其正确范围的值。用可用于其他域的信息重新计算 time->tm_wdaytime->tm_yday

目录

参数

time - 指向 std::tm 对象的指针,它指定要转换的本地日历时间

返回值

成功时为表示从纪元开始时间的 std::time_t 对象,若 time 不能表示成 std::time_t 对象则返回 -1 ( POSIX 亦要求此情况下存储 EOVERFLOWerrno 中)。

注意

std::tm 对象从 std::get_time 或 POSIX strptime 获得,则 tm_isdst 的值不确定,而且需要在调用 mktime 前显式设置。

示例

显示 100 个月前的时间。

#include <iostream>
#include <iomanip>
#include <ctime>
#include <stdlib.h>
 
int main()
{
    setenv("TZ", "/usr/share/zoneinfo/America/New_York", 1); // POSIX 限定
 
    std::time_t t = std::time(nullptr);
    std::tm tm = *std::localtime(&t);
    std::cout << "Today is           " << std::put_time(&tm, "%c %Z")
              << " and DST is " << (tm.tm_isdst ? "in effect" : "not in effect") << '\n';
    tm.tm_mon -= 100;  // tm_mon 现在在正常范围外
    std::mktime(&tm);  // tm_dst 不被设为 -1 ;使用今日的 DST 状态
    std::cout << "100 months ago was " << std::put_time(&tm, "%c %Z")
              << " and DST was " << (tm.tm_isdst ? "in effect" : "not in effect") << '\n';
}

输出:

Today is           Fri Apr 22 11:40:36 2016 EDT and DST is in effect
100 months ago was Sat Dec 22 10:40:36 2007 EST and DST was not in effect

参阅

转换纪元起时间到表示为本地时间的日历时间
(函数)
mktimeC 文档

版本历史

  • (当前 | 先前 2017年11月13日 (一) 00:30Fruderica讨论 | 贡献 . . (2,362字节) (+3). . (撤销)
  • 当前 | 先前 2017年10月10日 (二) 10:55Fruderica讨论 | 贡献. . (2,359字节) (-67). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 16:38P12bot讨论 | 贡献 . . (2,426字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 07:20P12bot讨论 | 贡献 . . (2,426字节) (-48). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 15:47P12bot讨论 | 贡献 . . (2,474字节) (+135). . (r2.7.3) (机器人添加:de, en, es, it, pt, ru 去除:zh) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 09:50P12讨论 | 贡献 . . (2,339字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (2,339字节) (-46). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 13:14P12讨论 | 贡献 . . (2,385字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (2,385字节) (+1,717). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年5月4日 (五) 11:15P12bot讨论 | 贡献 . . (668字节) (+109). . (r2.7.3) (机器人添加:en, fr, ja, pl) (撤销)
  • 当前 | 先前 2012年5月1日 (二) 03:36P12讨论 | 贡献 . . (559字节) (0). . (1个修订: Import from Dokuwiki) (撤销)
  • 当前 | 先前) 2012年5月1日 (二) 03:36P12讨论 | 贡献. . (559字节) (+559). . (Import from dokuwiki)