📜  C++ mktime()

📅  最后修改于: 2020-09-25 09:22:05             🧑  作者: Mango

C++中的mktime() 函数将本地日历时间转换为自纪元以来的时间,并将该值作为time_t类型的对象返回。

mktime() 函数在头文件中定义。

mktime()原型

time_t mktime(tm* time);

mktime 函数将指向tm对象的指针作为其参数,并返回自epoch以来的时间作为time_t类型的值。 time-> tm_wday和time-> tm_yday值将被忽略。

如果time->tm_isdst值为负,则它将使mktime尝试确定夏令时是否有效。

mktime()参数

mktime()返回值

示例:mktime() 函数如何工作?

#include 
#include 
using namespace std;

int main ()
{
    time_t tim;
    tm *ptr;

    int y = 2017, m = 4, d = 20;
    char weekday[7][20] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    
    time(&tim);
    ptr = localtime(&tim);

    // tm_year is time since 1900
    ptr->tm_year = y - 1900;
    ptr->tm_mon = m - 1;
    ptr->tm_mday = d;
    
    mktime (ptr);
    cout << "April 20, 2017 was " << weekday[ptr->tm_wday];
    
    return 0;
}

运行该程序时,输出为:

April 4, 2017 was a Thursday