字符转化时间 问:我想将字符转化为Ctime对象。 答:这有一个非常简单的函数,您可以在此上面加入你所需要的: BOOL ScanTime ( Ctime &time, // o - filled in time structure LPCTSTR lpszTime, // I - the string containing the time to be extracted LPCTSTR lpszFormat // I - the time format to extract according to ) { int nYear = 1980; // extracted time fields int nMonth = 1; int nDay = 1; int nHour = 0; int nMin = 0; int nSec = 0; int nFlag = DATE_TIME; // DATE_TIME / DATE_ONLY / TIME_ONLY Cstring msg; // start at the beginning char *pTime = (char *)lpszTime; char *pFmt = (char *)lpszFormat; while (*pFmt != '\0') { if (*pFmt == '%') { pFmt++; switch (*pFmt) { case 'Y' : // year with century sscanf (pTime,"%4d",&nYear); if (nYear <1980 || nYear> 2036) { msg.Format ("Invalid year (%d)",nYear); AfxMessageBox (msg); return (FALSE); } pTime+=4; break; case 'y' : // year without century (00-99) sscanf (pTime,"%2d",&nYear); nYear = nYear + (nYear > 36 ? 1900 : 2000); if (nYear <1980 || nYear> 2036) { msg.Format ("Invalid year (%d)",nYear); AfxMessageBox (msg); return (FALSE); } pTime+=2; break; case 'm' : // month (01-12) sscanf (pTime,"%2d",&nMonth); if (nMonth <1 || nMonth> 12) { msg.Format ("Invalid month (%d)",nMonth); AfxMessageBox (msg); return (FALSE); } pTime+=2; break; case 'd' : // day of month (01-31) sscanf (pTime,"%2d",&nDay); if (nDay <1 || nDay> 31) { msg.Format ("Invalid day (%d)",nDay); AfxMessageBox (msg); return (FALSE); } pTime+=2; break; case 'H' : // hour (00-23) sscanf (pTime,"%2d",&nHour); if (nHour <0 || nHour> 23) { msg.Format ("Invalid hour (%d)",nHour); AfxMessageBox (msg); return (FALSE); } pTime+=2; break; case 'M' : // minute (00-59) sscanf (pTime,"%2d",&nMin); if (nMin <0 || nMin> 59) { msg.Format ("Invalid minute (%d)",nMin); AfxMessageBox (msg); return (FALSE); } pTime+=2; break; case 'S' : // second (00-59) sscanf (pTime,"%2d",&nSec); if (nSec <1 || nSec> 31) { msg.Format ("Invalid second (%d)",nSec); AfxMessageBox (msg); return (FALSE); } pTime+=2; break; default : msg.Format("Invalid format specifier (%c)",*pFmt); AfxMessageBox(msg); return (FALSE); break; } } else { if (!isdigit((int)(*pTime))) { if (*pTime == *pFmt) { pTime++; } else { msg.Format ("Character mismatch : Expected %c, found %c",*pFmt,*pTime); AfxMessageBox ((LPCTSTR)msg); return (FALSE); } } } pFmt++; } // success time = Ctime(nYear,nMonth,nDay,nHour,nMin,nSec); return (TRUE); }