对下面代码进行本地调试
char str_time[50];
time_t now = time(NULL); //time(NULL)获得当前时区时间戳
strftime(str_time, 50, "%Y-%m-%d %H:%M:%S", gmtime(&now)); //将时间戳格式化存入str_time
cout << str_time << endl;
VS2022报错:
错误 C4996 ‘gmtime’: This function or variable may be unsafe. Consider using gmtime_s instead.
原因是某些 C 运行时库函数已弃用,因为它们不安全,并且具有更安全的变体。
tips: 不要求安全性的话可以直接在代码前添加警告杂则#pragma warning(disable : 4996)
关闭警告即可,方法不止于此
下面是不使用警告杂则的方法,即使用更安全的变体
代码如下:
time_t current = time(0);
char time[26];
ctime_s(time, sizeof time, ¤t);
cout<< "默认格式下当前时间" << time <<endl;
// 把 time 转换为 tm 结构
tm gmtm;
gmtime_s(&gmtm, ¤t); //将time_t类型的时间转换为struct tm类型的时间,存入gmtm
strftime(time, sizeof time, "%Y-%m-%d %H:%M:%S", &gmtm);
cout << "UTC日期和时间:" << time << endl;