当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ mktime()用法及代码示例


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

用法:

time_t  mktime( struct tm  *time_ptr )

参数:该函数接受强制性参数指针time_ptr,该指针指向包含要转换的日历时间的tm对象结构。


返回值:该函数返回两种类型的值,如下所述:

  • 如果传递的参数成功,则它将自纪元以来的时间作为类型time_t的对象返回。
  • 失败时返回-1。

以下示例程序旨在说明mktime()函数:

// CPP program to demonstrate the 
// mktime() function 
  
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    time_t tim; 
    tm* time_ptr; 
    char weekday[7][20] = { "Sunday", 
                            "Monday", 
                            "Tuesday", 
                            "Wednesday", 
                            "Thursday", 
                            "Friday", 
                            "Saturday" }; 
  
    // Date 
    int year = 2018; 
    int month = 6; 
    int day = 18; 
  
    time(&tim); 
    time_ptr = localtime(&tim); 
  
    // tm_year is time since 1900 
    time_ptr->tm_year = year - 1900; 
  
    // Months calculated since January 
    time_ptr->tm_mon = month - 1; 
  
    // Day calculated in the month 
    time_ptr->tm_mday = day; 
  
    // time_ptr pointer to be pass 
    mktime(time_ptr); 
  
    cout << "Tha Day on 18th June 2018 was "
         << weekday[time_ptr->tm_wday]; 
  
    return 0; 
}
输出:
Tha Day on 18th June 2018 was Monday


相关用法


注:本文由纯净天空筛选整理自jit_t大神的英文原创作品 mktime() function in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。