java判断日期是否合法

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

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

public static boolean judge(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(judge(a));
        System.out.println(judge(b));
        System.out.println(judge(c));
        System.out.println(judge(d));
        System.out.println(judge(e));
        System.out.println(judge(f));

    }

         输出结果如下:

true
true
true
false
false
false
  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值