//判断日期的合法性
int check_valid(int date)
{
int year = date / 10000;
int month = date % 10000 / 100;
int day = date % 100;
if (month <= 0 || month >= 13) return 0;
//一年十二个月,二月比较特殊,因此我们分开来讨论。
if (day == 0 || month != 2 && day > months[month]) return 0;
if (month == 2)
{
int leap = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0);//判断是否为闰年(闰年二月29天,平年二月28天)
if (day > 28 + leap) return 0;//二月最多29天
}
return 1;
}
//十二个月中每个月分别对应的天数(因为数组是从0开始的,而我们的月份是从一月开始的,因此设置的数组长度为13)
int months[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
//得到某年某月的天数
int get(int year, int month)
{
if (month != 2) return months[month];
else
{
// 2月
int leap = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0);
return 28 + leap;
}
}
具体代码及案例如下:
希望大家看了该模板,可以熟练应对日期,生日方面的问题。