Java中如何校验一个日期是否正确且合法

=Start=

缘由:

整理一下Java中校验一个日期是否正确且合法的方法,网上关于这类功能的代码很多,但质量参差不齐,且不保证正确性,所以自己在此整理一下自己验证过的内容,方便需要的时候参考和使用。

正文:

参考解答:

可行的方法:

  1. 自己按照原理进行编写
  2. SimpleDateFormat + setLenient(false)
  3. LocalDate (需要Java 8及以上版本)
  4. Apache Commons Validator 包
package com.example.learn;

import org.apache.commons.validator.GenericValidator;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;

public class DateUtils {

    public static String dateArray[] = {"2020-02-28","2020-02-29","2020-02-30","2020-02-31","2020-01-31","2019-02-29"};
    public static String datePattern = "yyyy-MM-dd";

    // Key is setLenient(false);
    public static boolean isValidDate(String dateString, String datePattern) {
        try {
            DateFormat df = new SimpleDateFormat(datePattern);
            df.setLenient(false);
            df.parse(dateString);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    // The java.time framework is built into Java 8 and later.
    public static boolean isValidDate2(String dateString) {
        boolean dateIsValid = true;
        try {
            int year = Integer.parseInt(dateString.substring(0,4));
            int month = Integer.parseInt(dateString.substring(5,7));
            int day = Integer.parseInt(dateString.substring(8,10));
            // System.out.println(String.format("%d\t%d\t%d", year, month, day));
            LocalDate.of(year, month, day);
        } catch (DateTimeException e) {
            dateIsValid = false;
        }
        return dateIsValid;
    }

    // The java.time framework is built into Java 8 and later.
    // Error case:
    // 2020-02-30: true
    // 2020-02-31: true
    // 2019-02-29: true
    public static boolean isValidDateFormat(String dateString, String pattern) {
        boolean valid = true;
        // DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern).withResolverStyle(ResolverStyle.STRICT);
        try {
            formatter.parse(dateString);
        } catch (DateTimeParseException e) {
            valid = false;
        }
        return valid;
    }


    static int MAX_VALID_YR = 9999;
    static int MIN_VALID_YR = 1900;

    // Judge is 闰年(leap year) or not ?
    static boolean isLeap(int year) {
        // Return true if year is a multiple of 4 and not multiple of 100.
        // OR year is multiple of 400.
        return (((year % 4 == 0) &&
                (year % 100 != 0)) ||
                (year % 400 == 0));
    }

    // Returns true if given year+month+day is valid, or false(not valid).
    static boolean isValidDate3(int y, int m, int d) {
        // If year, month and day // are not in given range
        if (y > MAX_VALID_YR || y < MIN_VALID_YR)
            return false;
        if (m < 1 || m > 12)
            return false;
        if (d < 1 || d > 31)
            return false;

        // Handle February month with leap year
        if (m == 2) {
            if (isLeap(y))
                return (d <= 29);
            else
                return (d <= 28);
        }

        // Months of April, June, Sept and Nov must have
        // number of days less than or equal to 30.
        if (m == 4 || m == 6 || m == 9 || m == 11)
            return (d <= 30);

        return true;
    }


    public static void main(String[] args) {
        System.out.println("SimpleDateFormat-setLenient");
        for (String dateStr: dateArray) {
            System.out.println(String.format("%s: %b", dateStr, isValidDate(dateStr, datePattern)));
        }

        System.out.println("\njava.time.LocalDate");
        for (String dateStr: dateArray) {
            System.out.println(String.format("%s: %b", dateStr, isValidDate2(dateStr)));
        }

        System.out.println("\ncommons-validator");
        for (String dateStr: dateArray) {
            System.out.println(String.format("%s: %b", dateStr, GenericValidator.isDate(dateStr, datePattern, true)));
        }

        System.out.println("\nvia default judgement");
        for (String dateStr: dateArray) {
            int year = Integer.parseInt(dateStr.substring(0,4));
            int month = Integer.parseInt(dateStr.substring(5,7));
            int day = Integer.parseInt(dateStr.substring(8,10));
            System.out.println(String.format("%s: %b", dateStr, isValidDate3(year, month, day)));
        }

        System.out.println("\nDateTimeFormatter");
        for (String dateStr: dateArray) {
            System.out.println(String.format("%s: %b", dateStr, isValidDateFormat(dateStr, datePattern)));
        }

    }
}

参考链接:

Program to check if a date is valid or not
https://www.geeksforgeeks.org/program-check-date-valid-not/

Check If a String Is a Valid Date in Java
https://www.baeldung.com/java-string-valid-date

https://github.com/eugenp/tutorials/tree/master/core-java-modules/core-java-datetime-string

https://mvnrepository.com/artifact/commons-validator/commons-validator/1.6

Java中如何校验一个日期是否正确?
https://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java
https://stackoverflow.com/a/4528094
https://stackoverflow.com/a/23438158

https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setLenient(boolean)

How to check if date is valid in Java
https://mkyong.com/java/how-to-check-if-date-is-valid-in-java/

=END=

声明: 除非注明,ixyzero.com文章均为原创,转载请以链接形式标明本文地址,谢谢!
https://ixyzero.com/blog/archives/4787.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注