C++ 標準庫沒有提供所謂的日期類型。C++ 繼承了 C 語言用于日期和時間操作的結(jié)構(gòu)和函數(shù)。為了使用日期和時間相關的函數(shù)和結(jié)構(gòu),需要在 C++ 程序中引用 <ctime> 頭文件。
有四個與時間相關的類型:clock_t、time_t、size_t 和 tm。類型 clock_t、size_t 和 time_t 能夠把系統(tǒng)時間和日期表示為某種整數(shù)。
結(jié)構(gòu)類型 tm 把日期和時間以 C 結(jié)構(gòu)的形式保存,tm 結(jié)構(gòu)的定義如下:
struct tm { int tm_sec; // 秒,正常范圍從 0 到 59,但允許至 61 int tm_min; // 分,范圍從 0 到 59 int tm_hour; // 小時,范圍從 0 到 23 int tm_mday; // 一月中的第幾天,范圍從 1 到 31 int tm_mon; // 月,范圍從 0 到 11 int tm_year; // 自 1900 年起的年數(shù) int tm_wday; // 一周中的第幾天,范圍從 0 到 6,從星期日算起 int tm_yday; // 一年中的第幾天,范圍從 0 到 365,從 1 月 1 日算起 int tm_isdst; // 夏令時 }
下面是 C/C++ 中關于日期和時間的重要函數(shù)。所有這些函數(shù)都是 C/C++ 標準庫的組成部分,您可以在 C++ 標準庫中查看一下各個函數(shù)的細節(jié)。
序號 | 函數(shù) & 描述 |
---|---|
1 | time_t time(time_t *time);
該函數(shù)返回系統(tǒng)的當前日歷時間,自 1970 年 1 月 1 日以來經(jīng)過的秒數(shù)。如果系統(tǒng)沒有時間,則返回 .1。 |
2 | char *ctime(const time_t *time);
該返回一個表示當?shù)貢r間的字符串指針,字符串形式 day month year hours:minutes:seconds year\n。 |
3 | struct tm *localtime(const time_t *time);
該函數(shù)返回一個指向表示本地時間的 tm 結(jié)構(gòu)的指針。 |
4 | clock_t clock(void);
該函數(shù)返回程序執(zhí)行起(一般為程序的開頭),處理器時鐘所使用的時間。如果時間不可用,則返回 .1。 |
5 | char * asctime ( const struct tm * time );
該函數(shù)返回一個指向字符串的指針,字符串包含了 time 所指向結(jié)構(gòu)中存儲的信息,返回形式為:day month date hours:minutes:seconds year\n\0。 |
6 | struct tm *gmtime(const time_t *time);
該函數(shù)返回一個指向 time 的指針,time 為 tm 結(jié)構(gòu),用協(xié)調(diào)世界時(UTC)也被稱為格林尼治標準時間(GMT)表示。 |
7 | time_t mktime(struct tm *time);
該函數(shù)返回日歷時間,相當于 time 所指向結(jié)構(gòu)中存儲的時間。 |
8 | double difftime ( time_t time2, time_t time1 );
該函數(shù)返回 time1 和 time2 之間相差的秒數(shù)。 |
9 | size_t strftime();
該函數(shù)可用于格式化日期和時間為指定的格式。 |
下面的實例獲取當前系統(tǒng)的日期和時間,包括本地時間和協(xié)調(diào)世界時(UTC)。
#include <iostream>
#include <ctime>
using namespace std;
int main( )
{
// 基于當前系統(tǒng)的當前日期/時間
time_t now = time(0);
// 把 now 轉(zhuǎn)換為字符串形式
char* dt = ctime(&now);
cout << "本地日期和時間:" << dt << endl;
// 把 now 轉(zhuǎn)換為 tm 結(jié)構(gòu)
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "UTC 日期和時間:"<< dt << endl;
}
當上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
本地日期和時間:Sat Jan 8 20:07:41 2011 UTC 日期和時間:Sun Jan 9 03:07:41 2011
tm 結(jié)構(gòu)在 C/C++ 中處理日期和時間相關的操作時,顯得尤為重要。tm 結(jié)構(gòu)以 C 結(jié)構(gòu)的形式保存日期和時間。大多數(shù)與時間相關的函數(shù)都使用了 tm 結(jié)構(gòu)。下面的實例使用了 tm 結(jié)構(gòu)和各種與日期和時間相關的函數(shù)。
在練習使用結(jié)構(gòu)之前,需要對 C 結(jié)構(gòu)有基本的了解,并懂得如何使用箭頭 -> 運算符來訪問結(jié)構(gòu)成員。
#include <iostream>
#include <ctime>
using namespace std;
int main(){
// 基于當前系統(tǒng)的當前日期/時間
time_t now = time(0);
cout << "1970年1月1日到目前經(jīng)過的秒數(shù):" << now << endl;
tm *ltm = localtime(&now);
// 輸出 tm 結(jié)構(gòu)的各個組成部分
cout << "年: "<< 1900 + ltm->tm_year << endl;
cout << "月: "<< 1 + ltm->tm_mon<< endl;
cout << "日: "<< ltm->tm_mday << endl;
cout << "時間: "<< 1 + ltm->tm_hour << ":";
cout << 1 + ltm->tm_min << ":";
cout << 1 + ltm->tm_sec << endl;
}
當上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
1970年1月1日到目前經(jīng)過的秒數(shù):1524456057 年: 2018 月: 4 日: 23 時間: 5:1:58
更多建議: