java如何验证时间合法性

这里推荐用我常用两种方式:

1. 运用数组来进行时间合法校验

public class test {
          
   
    //各个月中最大天数
    private static int[] days = {
          
   31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    public static void main(String[] args) {
          
   
        Scanner sc = new Scanner(System.in);
        System.out.println(judge(sc.nextInt(), sc.nextInt(), sc.nextInt()));
    }

    //判断日期合法性
    public static boolean judge(int year, int month, int day) {
          
   
        //首先判断月份是否合法
        if (month >= 1 && month <= 12) {
          
   
            //判断是否为闰年
            if ((year % 100 == 0 && year % 400 == 0) || year % 4 == 0) {
          
   
                //判断当前月份是否为2月,因为闰年的2月份为29天
                if (month == 2 && day <= 29) return true;
                else {
          
   
                    if (day <= days[month - 1]) return true;
                }
            } else {
          
   
                if (day <= days[month - 1]) return true;
            }
        }
        return false;
    }


}

2. 通过java8的特性来进行时间合法校验

public class test2 {
          
   
    /**
     * 验证字符串是否为指定日期格式
     *
     * @param oriDateStr 待验证字符串
     * @param pattern    日期字符串格式, 例如 "yyyy-MM-dd"
     * @return 有效性结果, true 为正确, false 为错误
     */
    public static boolean dateStrIsValid(String oriDateStr, String pattern) {
          
   
        if (StringUtils.isBlank(oriDateStr) || StringUtils.isBlank(pattern)) {
          
   
            return false;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        try {
          
   
            Date date = dateFormat.parse(oriDateStr);
            return oriDateStr.equals(dateFormat.format(date));
        } catch (ParseException e) {
          
   
            return false;
        }
    }
}

PS:在test2中是通过SimpleDateFormat函数来进行判断的,但是SimpleDateFormat是线程不安全的,如要考虑到线程安全性则可以用DateTimeFormat。(参考下面代码)

public static boolean legalDate(String oriDateStr, String pattern, int type) {
          
   
        if (StringUtils.isBlank(oriDateStr) || StringUtils.isBlank(pattern)) {
          
   
            return false;
        }
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);

        //判断日期
        if (type == 1) {
          
   
            LocalDate parse = LocalDate.parse(oriDateStr, df);
            return oriDateStr.equals(df.format(parse));
        } else {
          
   
            //精确到时间
            LocalDateTime parse = LocalDateTime.parse(oriDateStr, df);
            return oriDateStr.equals(df.format(parse));
        }
    }

谢谢观看,走过路过点个小赞!:p

经验分享 程序员 微信小程序 职场和发展