2 回答

TA貢獻1852條經(jīng)驗 獲得超7個贊
兩個時間大小的比較方法描述如下:
首先解析字符串,獲取年月日時分秒各項數(shù)值。然后按照先比較年月日,再比較時分秒的辦法進行比較。如果大于則返回1,如果小于返回0,如果等于返回2。
這里面需要利用到兩個知識點:
比較年月日,可以先將年月日整合為一個整數(shù),然后比較整數(shù)即可比較出年月日的大小
sscanf可以將字符串中的數(shù)值提取出來
代碼實現(xiàn)如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | int compare(const char* time1,const char* time2) { int year1,month1,day1,hour1,min1,sec1; int year2,month2,day2,hour2,min2,sec2; sscanf(time1,"%d-%d-%d %d:%d:%d",&year1,&month1,&day1,&hour1,&min1,&sec1); sscanf(time2,"%d-%d-%d %d:%d:%d",&year2,&month2,&day2,&hour2,&min2,&sec2); int tm1 = year1*10000+month1*100+day1; int tm2 = year2*10000+month2*100+day2; if(tm1!=tm2) return (tm1>tm2)?1:0;//如果相等,大返回1,小返回0 tm1 = hour1*3600+min1*60+sec1; tm2 = hour2*3600+min2*60+sec2;//將時分秒轉(zhuǎn)換為秒數(shù) if(tm1!=tm2) return (tm1>tm2)?1:0;//如果相等,大返回1,小返回0 return 2;//到這里必然是相等了 } |

TA貢獻1786條經(jīng)驗 獲得超13個贊
有這么復(fù)雜么 char str1[30] = "2015-08-06 09:32:60";
char str2[30] = "2015-04-06 09:32:59";這個時間 是控件獲取的還是手動輸入的?
如果是控件獲取的 一般是Ctime類型的,直接可以比較大??;如果手動輸入的 可以轉(zhuǎn)成Ctime類 然后再直接比較大小,再輸入的時候 控制一下就可以了;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | CTime timestr(LPSTR str) { USES_CONVERSION; LPSTR strSQL=str; int nYear, nMonth, nDate, nHour, nMin, nSec; nYear=nMonth=nDate=nHour=nMin=nSec=0; sscanf(strSQL, "%d-%d-%d %d:%d:%d", &nYear, &nMonth, &nDate, &nHour, &nMin, &nSec); CTime t(nYear, nMonth, nDate, nHour, nMin, nSec); return t; } 然后調(diào)用這個 CTime t1=timestr("2015-08-06 09:32:60"); CTime t2=timestr("2015-04-06 09:32:59"); int i=0; if(t1>t2) { i=1; } else if(t2>t1) { i=0; } else {i=-1;} |
- 2 回答
- 0 關(guān)注
- 449 瀏覽
添加回答
舉報