時間函數庫

僅限於1900年以後的運算

用tm型態來存取時間資訊,可存取內容如下
假設當前為2020/7/26 10:01:59

#include <ctime> tm info; info.tm_year = year-1900; //120 info.tm_mon = month-1; //6 info.tm_mday = day; //26 info.tm_hour = hour; //10 info.tm_min = minute; //1 info.tm_sec = second; ///59 info.tm_isdst = -1; //表是否為夏季時

接下來可以把這時間資訊轉換為1900/1/1到該時間資訊所經過的秒數
注意:mktime的參數為指標,回傳值為time_t型態

time_t sec=mktime(&info);

如果想計算這個天數過幾天(day)後的日期,可用把sec加上過多少秒後,再用localtime轉回原本的tm形式
注意:local的參數為指標,回傳值也是指標

sec+=day*24*60*60; //天數轉換秒 tm *result=localtime(&sec); //轉換為時間資訊形式

輸出時間
注意:year要加上1900,month要加1

cout << 1900+result->tm_year << "/" << setw(2) << setfill('0') << 1+result->tm_mon << "/" << setw(2) << setfill('0') << result->tm_mday << ' ' << setw(2) << setfill('0') << result->tm_hour << "/" << setw(2) << setfill('0') << result->tm_min << '/'; setw(2) << setfill('0') << result->tm_sec << '\n';

完整程式碼

#include <bits/stdc++.h> using namespace std; #define int long long signed main(){ tm info; info.tm_year = 2020-1900; //120 info.tm_mon = 7-1; //6 info.tm_mday = 26; //26 info.tm_hour = 10; //10 info.tm_min = 1; //1 info.tm_sec = 59; ///59 info.tm_isdst = -1; //表是否為夏季時 time_t sec=mktime(&info); int day=2; sec+=day*24*60*60; //天數轉換秒 tm *result=localtime(&sec); //轉換為時間資訊形式 cout << 1900+result->tm_year << "/" << setw(2) << setfill('0') << 1+result->tm_mon << "/" << setw(2) << setfill('0') << result->tm_mday << ' ' << setw(2) << setfill('0') << result->tm_hour << ":" << setw(2) << setfill('0') << result->tm_min << ':' << setw(2) << setfill('0') << result->tm_sec << '\n'; } //OUTPUT : 2020/07/28 10:01:59

asctime這個函式可以把struct tm轉成字串形式。

printf("%s",asctime(&info)); //Sun Jul 26 10:01:59 2020

ctime這個函式可以把time_t型別轉成字串形式。

printf("%s",ctime(&sec)); //Sun Jul 26 10:01:59 2020
Select a repo