最近整理了一个判断日期合法性的函数,比较简洁,供大家参考,欢迎批评指正。
bool Check_date(short w_year,char w_month,char w_date)
{
char Month_buf[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }; //月份修正表
if (w_month==2) //闰年2月+1天
(((w_year%4==0)&&(w_year%100!=0))||(w_year%400==0))?Month_buf[1]+=1:Month_buf[1];
if (w_month>12||w_month<1||w_date>Month_buf[w_month-1]||w_date<1) //判断月份日期是否合法
return false;
return true;
}
下面是一个小测试;
typedef struct
{
short year;
char month;
char date;
}_Date;
_Date _date[8] =
{
2000,2,29,
1900,2,29,
2019,6,15,
2019,13,15,
2019,6,0,
2019,0,5,
2019,6,31,
2019,7,31,
};
int main()
{
for (int i = 0; i < 8; i++)
{
printf("%d-%d-%d\r\n", _date[i].year, _date[i].month, _date[i].date);
if (Check_date(_date[i].year, _date[i].month, _date[i].date) == true)
printf("该日期正确!\r\n");
else
printf("该日期错误!\r\n");
}
return 0;
}
运行结果如下:

本文分享了一个简洁的日期合法性检查函数,能够准确判断日期是否有效,包括闰年的处理。通过一系列测试案例验证了函数的准确性。
9499

被折叠的 条评论
为什么被折叠?



