名稱空間
變體
操作

std::mktime

來自 cppreference.com
< cpp‎ | chrono‎ | c
 
 
 
 
定義於標頭檔案 <ctime>
std::time_t mktime( std::tm* time );

將本地日曆時間轉換為自紀元以來的時間,表示為 std::time_t 物件。time->tm_wdaytime->tm_yday 被忽略。time 中的值可以超出其正常範圍。

如果 time->tm_isdst 的值為負,mktime 將嘗試確定夏令時是否生效。

如果轉換成功,time 物件將被修改。time 的所有欄位都將被更新以適應其適當的範圍。time->tm_wdaytime->tm_yday 將使用其他欄位中可用的資訊重新計算。

目錄

[編輯] 引數

time - 指向 std::tm 物件的指標,指定要轉換的本地日曆時間

[編輯] 返回值

成功時返回自紀元以來的時間,表示為 std::time_t 物件;如果 time 無法表示為 std::time_t 物件,則返回 -1

[編輯] 注意

如果 std::tm 物件是從 std::get_time 或 POSIX strptime 獲取的,則 tm_isdst 的值是不確定的,需要在使用 mktime 之前明確設定。

[編輯] 示例

顯式構造本地時間。

#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
 
int main()
{
    setenv("TZ", "/usr/share/zoneinfo/America/Los_Angeles", 1); // POSIX-specific
 
    std::tm tm{}; // Zero initialise
    tm.tm_year = 2020 - 1900; // 2020
    tm.tm_mon = 2 - 1; // February
    tm.tm_mday = 15; // 15th
    tm.tm_hour = 10;
    tm.tm_min = 15;
    tm.tm_isdst = 0; // Not daylight saving
    std::time_t t = std::mktime(&tm); 
    std::tm local = *std::localtime(&t);
 
    std::cout << "local: " << std::put_time(&local, "%c %Z") << '\n';
}

可能的輸出

local: Sat Feb 15 10:15:00 2020 PST

[編輯] 另請參閱

將自紀元以來的時間轉換為以本地時間表示的日曆時間
(函式) [編輯]
C 文件 關於 mktime