首页 > 解决方案 > 如何使用java检查像“08-Nov-2011”这样的字符串是否是有效日期?

问题描述

我想检查输入字符串是否为有效日期。字符串就像:- "08-Nov-2011" "21 Mar 2019"

爪哇代码:-

boolean checkFormat;
String input = "08-Nov-2011";
if (input.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
     checkFormat=true;
else
     checkFormat=false;

 System.out.println(checkFormat);

我正在考虑拆分,然后检查它的长度,例如第一个拆分词的长度为 2,第二个拆分词的长度为 3,最后一个词的长度为 4。

但是如果输入字符串是这样的: - AB-000-MN89 那么这里它会失败。

请帮我解决这个问题。

标签: javaregex

解决方案


正如几条评论中所述,确定您的日期是否有效的最佳方法是尝试使用 ajava.time.format.DateTimeFormatter类型的日期对象解析它LocalDate
您可以支持多种模式和/或使用类中的内置模式DateTimeFormatter

public static void main(String[] args) {
    // provide some patterns to be supported (NOTE: there are also built-in patterns!)
    List<String> supportedPatterns = new ArrayList<>();
    supportedPatterns.add("dd.MMM.yyyy");
    supportedPatterns.add("dd MMM yyyy");
    supportedPatterns.add("dd-MMM-yyyy");
    supportedPatterns.add("dd/MMM/yyyy");
    supportedPatterns.add("ddMMMyyyy");

    // define some test input
    String input = "08-Nov-2011";

    // provide a variable for each, pattern and the date
    String patternThatWorked = null;
    LocalDate output = null;

    // try to parse the input with the supported patterns
    for (String pattern : supportedPatterns) {
        try {
            output = LocalDate.parse(input, DateTimeFormatter.ofPattern(pattern));
            // until it worked (the line above this comment did not throw an Exception)
            patternThatWorked = pattern; // store the pattern that "made your day" and exit the loop
            break;
        } catch (DateTimeParseException e) {
            // no need for anything here but telling the loop to do the next try
            continue;
        }
    }

    // check if the parsing was successful (output must have a value)
    if (output != null) {
        System.out.println("Successfully parsed " + input 
                + " to " + output.format(DateTimeFormatter.ISO_LOCAL_DATE) // BUILT-IN pattern!
                + " having used the pattern " + patternThatWorked);
    }
}

这输出

Successfully parsed 08-Nov-2011 to 2011-11-08 having used the pattern dd-MMM-yyyy

推荐阅读