1. 有时需要用struct tm 对time_t赋值,注意tm赋值时,year-1900,month-1
2.另外注意sscanf的应用,例:
char strSource[20] = "1998 8 str";
int a,b;
char strDes[20];
memset(strDes,0,sizeof(strDes));
sscanf(strSource,"%d %d %s",&a,&b,strDes);// a = 1998,b = 2,strDes(str)
3.源程序
/*==============================================================================*/
// convert string whick like "yyyy-mm-dd hh:mm:ss" to time_t
// if successed convert, return true, else return false.
/*==============================================================================*/
bool ConvertDateTimeStringToTime_t(char * const str_time, time_t & tTmp)
{
char strTime[32];
memset(strTime,0,sizeof(strTime));
memcpy(strTime, str_time, sizeof(strTime));
long time = 0;// tmp value
char *ptr, seps[8] = "-. :////";
struct tm tp;
bool IsSuccConvert = false;// the convert result
memset(&tp, 0, sizeof(tp));
// use strtok to get the time
do{
if((ptr = strtok(strTime, seps)) == NULL)
break;
sscanf(ptr, "%d", &time);
tp.tm_year = time - 1900;// year - 1900!!!
if((ptr = strtok(NULL, seps)) == NULL)
break;
sscanf(ptr, "%d", &time);
tp.tm_mon = time - 1;// month - 1!!!
if((ptr = strtok(NULL, seps)) == NULL)
break;
sscanf(ptr, "%d", &time);
tp.tm_mday = time;
if((ptr = strtok(NULL, seps)) == NULL)
break;
sscanf(ptr, "%d", &time);
tp.tm_hour = time;
if((ptr = strtok(NULL, seps)) == NULL)
break;
sscanf(ptr, "%d", &time);
tp.tm_min = time;
if((ptr = strtok(NULL, seps)) == NULL)
break;
sscanf(ptr, "%d", &time);
tp.tm_sec = time;
tp.tm_isdst = -1;
tTmp = mktime(&tp);
IsSuccConvert = true;
}while(0);
return IsSuccConvert;
}
/*** get time function ***/
void getTime()
{
char ctVal[32] = "2007-09-03 11:20:20";
time_t tTmp;
ConvertDateTimeStringToTime_t(ctVal,tTmp);
CTime ctConvertTime(tTmp);
CString str = ctConvertTime.Format("%Y%m%d%H%M%S");
AfxMessageBox(str);
}
// 输出为 20070903112020