0
点赞
收藏
分享

微信扫一扫

java判断日期是否合法

夕阳孤草 2022-02-12 阅读 178

        参加蓝桥杯,现在把我认为好一点的算法记录下来。

        看到蓝桥杯真题有些是有和日期相关的题。这些题大部分是要判断一个日期是否合法。然后我就总结出了一个通俗易懂的算法。希望能用得上。

public static boolean juge(int date) {

//先将年月日取出来
int year = date / 10000;
int month = (date % 10000) / 100;
int day = date % 100;

//定义一个数组,数组里是每个月的合法天数
int[] arr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

//判断平年闰年
if ( ( year % 4 == 0 && year % 100 != 0 ) || ( year % 400 == 0 ) ) {
arr[1] = 29;//闰年二月有29天
} else {
arr[1] = 28;//平年二月有28天
}

//首先月份只有1到12月
if (month > 0 && month < 13) {
if ( day <= arr[month - 1] && day > 0 ) { //天数从0到该月的最大天数
return true; //如果合法,返回true
}
}
return false;
}

        这个算法传入的参数是int类型,格式像:20200202,20220212,19491001,这种。以上三个日期当然是正确的,但像20191314,20030229,20250000,这些就不合法了。

        以下是代码测试: 

public class Main {
public static void main(String[] args) {

int a = 20200202;
int b = 20220212;
int c = 19491001;
int d = 20191314;
int e = 20030229;
int f = 20250000;

System.out.println(juge(a));
System.out.println(juge(b));
System.out.println(juge(c));
System.out.println(juge(d));
System.out.println(juge(e));
System.out.println(juge(f));

}

         输出结果如下:

true
true
true
false
false
false
举报

相关推荐

0 条评论