情景:
当使用mfc 连接mysql 数据库后。在数据库中建表使用了日期 datetime 类型。表示的是年月日时分秒。而在mfc端接收后,若用c语言进行处理。在结果集MYSQL_RES中,是以char指针指向存储内容的。此时可以将内容转换为CString类型。CString 类型的构造函数中可以直接通过char*构造对象。
CString 转换为CTime:
//第一种方法:
MYSQL_ROW row=NULL;
row=mysql_fetch_row(result); //结果集的第一行 中的第二列为datetime类型
CString res(row[1]); //可以通过CSting构造函数直接初始化为CString类型
//将CString 转换为CTime类型
COleVariant vtime(res);
vtime.ChangeType(VT_DATE);
COleDateTime cOleTime=vtime;
SYSTEMTIME systime;
VariantTimeToSystemTime(cOleTime, &systime);
CTime cTimeFromDB(systime); //最后的cTimeFromDB为CTime类型
//第二种办法:
//思想:datetime 结构显示是年-月-日 时:分:秒 例如: 2020-04-02 09:23:43
//通过开始的叙述我们知道 这样的结果在mfc端是char* 指向的。所以只需要将这些数字提取出来构造个
//CTime 类型即可。
CString year,month,day,hour,minute,second;
year = lstr.Left(lstr.Find('-'));
month = lstr.Mid(lstr.Find('-')+1,lstr.ReverseFind('-')-lstr.Find('-')-1);
day = lstr.Right(lstr.GetLength() - lstr.ReverseFind('-')-1);
hour = rstr.Left(rstr.Find(':'));
minute = rstr.Mid(rstr.Find(':')+1,rstr.ReverseFind(':')-rstr.Find(':')-1);
second = rstr.Right(rstr.GetLength() - rstr.ReverseFind(':')-1);
char *yearstr = (char*)(LPCTSTR)year;
char *monthstr = (char*)(LPCTSTR)month;
char *daystr = (char*)(LPCTSTR)day;
char *hourstr = (char*)(LPCTSTR)hour;
char *minutestr = (char*)(LPCTSTR)minute;
char *secondstr = (char*)(LPCTSTR)second;
int dyear = atoi(yearstr);
int dmonth = atoi(monthstr);
int dday = atoi(daystr);
int dhour = atoi(hourstr);
int dminute = atoi(minutestr);
int dsecond = atoi(secondstr);
CTime time(dyear,dmonth,dday,dhour,dminute,dsecond);
对CTime进行加减操作
//对于CTime的加减日期操作,需要用到CTimeSpan类,表示的是绝对时间。
//可以通过简单的构造出一个CTimeSpan对象
CTimeSpan span(0,1,30,0); //表示的是1小时30分钟
CTime time_now = CTime::GetCurrentTime(); //获取当前系统时间
CTime time_new =time_now+span;
//time_new 为系统一个半小时以后的时间,注意的是'+'号的右侧为CTimeSpan类型。
参考文章: