在做项目的过程中,有些程序结果需要输出报告文件,而在报告文件中往往需要当前日期和时间。因此使用头文件time.h中的tm结构和localtime_s函数获取当前的日期和时间,具体可参考http://www.cplusplus.com/reference/ctime/localtime/。
程序如下:
#include "time.h"
void main()
{
struct tm tmInfo; //定义tm结构体变量
time_t now; //定义time_t变量
//获取当前日期和时间
time(&now);
localtime_s(&tmInfo, &now);
cout << tmInfo.tm_year + 1900 << "-" << tmInfo.tm_mon + 1 << "-" << tmInfo.tm_mday << endl;
cout << tmInfo.tm_hour << ":" << tmInfo.tm_min << ":" << tmInfo.tm_sec << endl;
}
程序结果如下: