如何使用时间API检查字符串是否与日期模式匹配?

12 java datetime-format datetime-parsing java-8 java-time

我的程序正在将输入字符串解析为LocalDate对象.在大多数情况下,字符串看起来像30.03.2014,但偶尔看起来像3/30/2014.根据具体情况,我需要使用不同的模式来调用DateTimeFormatter.ofPattern(String pattern).基本上,我需要检查字符串是否与模式匹配,dd.MM.yyyy或者M/dd/yyyy在进行解析之前.

正则表达式的方法类似于:

LocalDate date;
if (dateString.matches("^\\d?\\d/\\d{2}/\\d{4}$")) {
  date = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("M/dd/yyyy"));  
} else {
  date = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd.MM.yyyy"));  
}
Run Code Online (Sandbox Code Playgroud)

这有效,但在匹配字符串时使用日期模式字符串会很好.

有没有任何标准方法可以使用新的Java 8时间API执行此操作,而无需使用正则表达式匹配?我查看过文档,DateTimeFormatter但找不到任何内容.

Ale*_* C. 12

好的,我要继续发布它作为答案.一种方法是创建将保存模式的类.

public class Test {
    public static void main(String[] args){
        MyFormatter format = new MyFormatter("dd.MM.yyyy", "M/dd/yyyy");
        LocalDate  date = format.parse("3/30/2014"); //2014-03-30
        LocalDate  date2 = format.parse("30.03.2014"); //2014-03-30
    }
}

class MyFormatter {
    private final String[] patterns;

    public MyFormatter(String... patterns){
        this.patterns = patterns;
    }

    public LocalDate parse(String text){
        for(int i = 0; i < patterns.length; i++){
            try{
                return LocalDate.parse(text, DateTimeFormatter.ofPattern(patterns[i]));
            }catch(DateTimeParseException excep){}
        }
        throw new IllegalArgumentException("Not able to parse the date for all patterns given");
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以通过@MenoHochschild直接创建一个DateTimeFormatterString你在构造函数中传递的数组的数组来改进它.


另一种方法是使用a DateTimeFormatterBuilder,附加你想要的格式.可能存在其他一些方法,我没有深入了解文档:-)

DateTimeFormatter dfs = new DateTimeFormatterBuilder()
                           .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd"))                                                                 
                           .appendOptional(DateTimeFormatter.ofPattern("dd.MM.yyyy"))                                                                                     
                           .toFormatter();
LocalDate d = LocalDate.parse("2014-05-14", dfs); //2014-05-14
LocalDate d2 = LocalDate.parse("14.05.2014", dfs); //2014-05-14
Run Code Online (Sandbox Code Playgroud)