C++:日期以STRING格式输入,如何判断是否yyyy:mm:dd格式?若是则如何判断日期是否合理?最后附上代码。

如题所述

判断字符串的长度,两个冒号的位置,再判断除冒号外的字符是否都是数字, 如果符合 就说明是
yyyy:mm:dd格式,然后得到yyyy,mm,dd的具体数据,判断是否符合时间格式。

#include <string>
using namespace std;

#define FORMATE_ERROR 1 //格式错误
#define TIME_ERROR 2 //时间不合理
#define TIME_OK 3 //时间正确

bool IsLeapYear(int nyear);
int CheckString(string strTime);

int _tmain(int argc, _TCHAR* argv[])
{
string strTime = "1240:11:31";

int nRet = CheckString(strTime);
if (nRet == FORMATE_ERROR)
{
printf("格式错误\n");
}
else if (nRet == TIME_ERROR)
{
printf("时间不合理\n");
}
else
{
printf("时间正确\n");
}

system("pause");

return 0;
}

int CheckString(string strTime)
{
//判断字符串长度
if (strTime.length() != 10)
{
return FORMATE_ERROR;
}

//判断冒号位置
if (strTime[4] != ':' || strTime[7] != ':')
{
return FORMATE_ERROR;
}

//判断是否都是数字
for (int i = 0; i < strTime.length(); ++i)
{
if (i != 4 && i != 7)
{
if (strTime[i] < '0' || strTime[i] >'9')
{
return FORMATE_ERROR;
}
}
}

//判断数字是否合理
int nyear = 0;
int nmonth = 0;
int nday = 0;

sscanf(strTime.c_str(),"%d:%d:%d",&nyear,&nmonth,&nday);

if (nyear <= 0)
{
return TIME_ERROR;
}

if (nmonth > 12 || nmonth < 1)
{
return TIME_ERROR;
}

//判断每月的最大天数
int nMaxDays = 0;

if (nmonth == 2)
{
if (IsLeapYear(nyear))
{
nMaxDays = 29;
}
else
{
nMaxDays = 28;
}
}

else if (nmonth == 1 || nmonth == 3 || nmonth == 5 || nmonth == 7 || nmonth == 8 || nmonth == 10 || nmonth == 12)
{
nMaxDays = 31;
}
else
{
nMaxDays = 30;
}

if (nday < 0 || nday > nMaxDays)
{
return TIME_ERROR;
}

return TIME_OK;

}

//判断是否闰年
bool IsLeapYear(int nyear)
{
if (nyear%400 == 0)
{
return true;
}

if (nyear%4 == 0)
{
if (nyear%100 == 0)
{
return false;
}
else
{
return true;
}
}
return false;
}

代码写的太蠢了,年具体怎么算合理,自己再改改,可能用ctime类判断更好,我不会用那个类
温馨提示:答案为网友推荐,仅供参考
相似回答