在 C++ 中列印系統時間
C++ 標準庫未提供合適的日期型別。C++ 從 C 繼承了用於日期和時間操作的結構和函式。要訪問與日期和時間相關的函式和結構,您需要在 C++ 程式中包含 <<ctime> 標標頭檔案。
有四種與時間相關的型別:clock_t、time_t、size_t 和 tm。clock_t、size_t 和 time_t 型別能夠以某種整數形式表示系統時間和日期。
結構型別 tm 以 C 結構的形式儲存日期和時間,其包含以下元素 -
struct tm {
int tm_sec; // seconds of minutes from 0 to 61
int tm_min; // minutes of hour from 0 to 59
int tm_hour; // hours of day from 0 to 24
int tm_mday; // day of month from 1 to 31
int tm_mon; // month of year from 0 to 11
int tm_year; // year since 1900
int tm_wday; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
}假設您想檢索當前系統日期和時間,作為本地時間或協調世界時間 (UTC)。以下是實現上述目的的示例 –
示例
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
char* dt = ctime(&now); // convert now to string form
cout << "The local date and time is: " << dt << endl;
// convert now to tm struct for UTC
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
}輸出
The local date and time is: Fri Mar 22 13:07:39 2019 The UTC date and time is:Fri Mar 22 07:37:39 2019
廣告
資料結構
網路連線
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP