C++ 标准库没有提供所谓的日期类型。C++ 继承了 C 语言用于日期和时间操作的结构和函数。为了使用日期和时间相关的函数和结构,需要在 C++ 程序中引用 <ctime> 头文件。
有四个与时间相关的类型:clock_t、time_t、size_t 和 tm。类型 clock_t、size_t 和 time_t 能够把系统时间和日期表示为某种整数。
以 20**-**-** **:**:** 格式输出当前日期:
#include <iostream>
#include <ctime>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
string Get_Current_Date();
int main( )
{
// 将当前日期以 20** - ** - ** 格式输出
cout << Get_Current_Date().c_str() << endl;
getchar();
return 0;
}
string Get_Current_Date()
{
time_t nowtime;
nowtime = time(NULL); //获取日历时间
char tmp[64];
strftime(tmp,sizeof(tmp),"%Y-%m-%d %H:%M:%S",localtime(&nowtime));
return tmp;
}
输出格式类似:
2018-09-19 09:00:58
vs2017 上使用安全方法:
#include <iostream>
#include <ctime>
using namespace std;
#define TIMESIZE 26
int main() {
// 时间
time_t now = time(0);
char dt[TIMESIZE];
errno_t err;
err = ctime_s(dt, TIMESIZE, &now);
cout << "local time: " << dt << endl;
cout << "timestamp: " << now << endl;
struct tm ltm;
localtime_s(<m, &now);
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;
return 0;
}
例 1 本地时间和格林威治时间安全的写法:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
struct tm tmnow;
char dt[100];
// 基于当前系统的当前日期/时间
time_t now = time(0);
// 把 now 转换为字符串形式
ctime_s(dt,100,&now);
cout << "本地日期和时间:" << dt << endl;
// 把 now 转换为 tm 结构
gmtime_s(&tmnow,&now);
asctime_s(dt ,&tmnow);
cout << "UTC 日期和时间:" << dt<< endl;
}
在VS 2013中运行此程序会出现如下错误:
1>error C4996: 'ctime': This function or variable may be unsafe. Consider using ctime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========
查阅之后,发现加入#pragma warning(disable : 4996)【如果您确定代码中没有安全问题,可以通过禁用此功能#pragma warning(disable : 4996)。】
之后就可以了。