当前位置:   article > 正文

java如何验证时间合法性_java判断日期是否合法

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;
    }


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

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;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

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));
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/52183
推荐阅读
相关标签
  

闽ICP备14008679号