C++ 日期 & 时间
有四个与时间相关的类型:clock_t、time_t、size_t 和 tm。类型 clock_t、size_t 和 time_t 能够把系统时间和日期表示为某种整数。
实例
#include <iostream>
#include <ctime>
using namespace std;
int main( ){
// 基于当前系统的当前日期/时间
time_t now = time(0);
// 把 now 转换为字符串形式
char* dt = ctime(&now);
cout << "本地日期和时间:" << dt << endl;
// 把 now 转换为 tm 结构 tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "UTC 日期和时间:"<< dt << endl;
}
当上面的代码被编译和执行时,它会产生下列结果:
本地日期和时间:Sat Jan 8 20:07:41 2011 UTC 日期和时间:Sun Jan 9 03:07:41 2011
实例
#include <iostream>
#include <ctime>
using namespace std;
int main( ){
// 基于当前系统的当前日期/时间
time_t now = time(0);
cout << "1970 到目前经过秒数:" << now << endl;
tm *ltm = localtime(&now);
// 输出 tm 结构的各个组成部分
cout << "年: "<< 1900 + ltm->tm_year << endl;
cout << "月: "<< 1 + ltm->tm_mon<< endl;
cout << "日: "<< ltm->tm_mday << endl;
cout << "时间: "<< ltm->tm_hour << ":";
cout << ltm->tm_min << ":";
cout << ltm->tm_sec << endl;
}
当上面的代码被编译和执行时,它会产生下列结果:
1970 到目前时间:1503564157 年: 2017 月: 8 日: 24 时间: 16:42:37