这本来应该不算个事儿,可当我前几天遇到这个具体的问题时还是着实地费了点周折。写下来,供参考。
【我的思路】
1. CTime类的其中一个构造方法如下,而其参数却有如下的约束,否则ASSERT会跳出来。所以判断的前提是这6项分别在下面这个范围内。
CTime time4(1999, 3, 19, 22, 15, 0); // 10:15PM March 19, 1999
CTime( int, int, ...); Constructs a CTime object from local time components with each component constrained to the following ranges:
Component | Range |
---|---|
nYear | 1970–3000 |
nMonth | 1–12 |
nDay | 1–31 |
nHour | 0-23 |
nMin | 0-59 |
nSec | 0-59 |
2. 使用上面的1的构造方法构建一个CTime的对象后,比较年月日时分秒各字段与构造方法的输入是否一致。
// Example for CTime::GetDay, CTime::GetMonth, and CTime::GetYear CTime t(1999, 3, 19, 22, 15, 0); // 10:15 PM March 19, 1999 ATLASSERT(t.GetDay() == 19); ATLASSERT(t.GetMonth() == 3); ATLASSERT(t.GetYear() == 1999);
【具体代码】
bool bCheckDate(int nYear, int nMonth, int nDay, int nHour, int nMinute, int nSecond)
{
if (nYear < 1970|| nYear > 3000 ||
nMonth < 1 || nMonth> 12 ||
nDay < 1 || nDay > 31 ||
nHour < 0 || nHour > 23 ||
nMinute<0 || nMinute>59 ||
nSecond<0 || nSecond>59 ){
return false;
}
CTime t(nYear, nMonth, nDay, nHour, nMinute, nSecond);
return (nYear == t.GetYear() &&
nMonth == t.GetMonth() &&
nDay == t.GetDay() &&
nHour == t.GetHour() &&
nMinute == t.GetMinute() &&
nSecond == t.GetSecond());
}
【最后】
可能 会以有人会怀疑,这玩意能好用吗,月大月小(30,31)能处理好吗,还有那烦人的闰月(28,29)呢?
其实都完全能处理好。因为一旦转换成Ctime类对象后,其内部表示就是一个长长的数字而已。
如果你输入了4月31号这样的日期,CTime构造时不会报错而是将其自动“进位”转换成了5月1号。
同理,如果是非闰年的2月29号,则会转成3月1号;更进一步地讲,非闰年的2月31号会被转成3月3号!