一次使用MFC调用MYSQL的过程中,对sql语句的处理时,需要用到时间戳和日期的互相转换,采用C库的struct tm做法,会产生secure报错,即时在函数名后加上_s也仍然无法解决。于是有了下述办法,俺是初学者,有更好的办法请大佬们指教。
首先引入头文件
#include<ctime>
#include<iostream>
using namespace std;
获取当前系统的时间戳
time_t t;
t = time(NULL);//time(NULL)能返回一个当前时间的时间戳。此时获得的t已经是时间戳,直接可以赋值给int类型的变量
int timestamp=t;//系统会提示这是有损转换,实际上可以忽略。
获取当前系统的日期
CTime mtime;//定义一个CTime类对象,其中CTime是MFC库中的类
mtime = CTime::GetCurrentTime();//获取当前系统日期
int year = m_time.GetYear();
int month = m_time.GetMonth();
int cday = m_time.GetDay();
int hour = m_time.GetHour();
int minute = m_time.GetMinute();
int secend = m_time.GetSecond();
将日期转为string类型,此时通过to_string()已经可以在写入mysql请求中。
string m = "" + to_string(year) + "-"+to_string(month)+"-"+to_string(cday)+"";
以下是将该日期再转回时间戳(借用的大佬写好的函数),函数运行的值同样可以赋值给int类型变量,该函数的参数是const char*类型,因此可以再将string m转成const char*类型后调用
time_t convert_str_to_tm(const char * str_time)//日期转时间戳函数
{
struct tm tt;
memset(&tt, 0, sizeof(tt));
tt.tm_year = atoi(str_time) - 1900;
tt.tm_mon = atoi(str_time + 5) - 1;
tt.tm_mday = atoi(str_time + 8);
//tt.tm_hour = atoi(str_time + 11);
//tt.tm_min = atoi(str_time + 14);
//tt.tm_sec = atoi(str_time + 17);
return mktime(&tt);
}//这里我只用到了年月日,需要时分秒的同学,可以把hour等处的注释去掉
将string类型的m转换成const char *类型变量
cdate = m.c_str();//同样调用c_str()函数