C++ 标准库没有提供所谓的日期类型。C++ 继承了 C 语言用于日期和时间操作的结构和函数。为了使用日期和时间相关的函数和结构,需要在 C++ 程序中引用 头文件。
有四个与时间相关的类型:clock_t、time_t、size_t 和 tm。类型 clock_t、size_t 和 time_t 能够把系统时间和日期表示为某种整数。
结构类型 tm 把日期和时间以 C 结构的形式保存,tm 结构的定义如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| 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 年起的年数 int tm_wday; // 一周中的第几天,范围从 0 到 6,从星期日算起 int tm_yday; // 一年中的第几天,范围从 0 到 365,从 1 月 1 日算起 int tm_isdst; // 夏令时 }
#include <iostream> #include <ctime> using namespace std; int main(){ time_t t = time(0); cout << "now time: " << t << endl;
char *ti = ctime(&t); cout << "now string time: " << ti << endl;
tm* tim = localtime(&t); cout << "==============time struct===================" << endl; cout << "year: " << 1900 + tim->tm_year << endl; cout << "month: " << 1 + tim->tm_mon << endl; cout << "day: " << tim->tm_mday << endl; cout << "year day: " << tim->tm_yday << endl; cout << "week day: " << tim->tm_wday << endl; cout << "hour: " << tim->tm_hour << endl; cout << "minutes: " << tim->tm_min << endl; cout << "second: " << tim->tm_sec << endl; cout << "is dst: " << tim->tm_isdst << endl; cout << "==============time struct===================" << endl;
cout << "runing send time is: " << clock()/1000 << 's' << endl;
ti = asctime(tim); cout << "struct to string time: " << ti << endl;
time_t tt; time(&tt);
tm *timm = gmtime(&tt); printf("当前的世界时钟:\n"); printf("伦敦:%2d:%02d\n", (timm->tm_hour+1)%24, timm->tm_min); printf("中国:%2d:%02d\n", (timm->tm_hour+8)%24, timm->tm_min);
tt = mktime(timm);
cout << "now time: " << tt << endl;
time_t tc = difftime(t,tt); cout << "time part: " << tc << endl;
time_t rawtime; struct tm *info; char buffer[80];
time( &rawtime );
info = localtime( &rawtime );
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info); printf("格式化的日期 & 时间 : %s\n", buffer );
return 0; }
|