std::mktime
来自cppreference.com
| 定义于头文件 <ctime>
|
||
| std::time_t mktime( std::tm* time ); |
||
转换本地日历时间为从纪元起的时间,作为 time_t 对象。忽略 time->tm_wday 与 time->tm_yday 。容许 time 中的值在其正常范围外。
time->tm_isdst 的负值会导致 mktime 尝试确定在指定时间夏时令是否有效。
若转换到 time_t 成功,则修改 time 会被修改。更新 time 的所有域为符合其正确范围的值。用可用于其他域的信息重新计算 time->tm_wday 与 time->tm_yday 。
参数
| time | - | 指向 std::tm 对象的指针,它指定要转换的本地日历时间 |
返回值
成功时为表示从纪元开始时间的 std::time_t 对象,若 time 不能表示成 std::time_t 对象则返回 -1 ( POSIX 亦要求此情况下存储 EOVERFLOW 于 errno 中)。
注意
若 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
参阅
| 转换纪元起时间为以本地时间表示的日历时间 (函数) |