解析日期的优雅解决方案

hel*_*elt 4 java datetime java-8 java-time

我想将一些文本解析为日期.但是,无法保证文本具有所需的格式.这可能是2012-12-12或者2012甚至.

Currently, I am down the path to nested try-catch blocks, but that's not a good direction (I suppose).

LocalDate parse;
try {
    parse = LocalDate.parse(record, DateTimeFormatter.ofPattern("uuuu/MM/dd"));
} catch (DateTimeParseException e) {
    try {
        Year year = Year.parse(record);
        parse = LocalDate.from(year.atDay(1));
    } catch (DateTimeParseException e2) {
        try {
              // and so on 
        } catch (DateTimeParseException e3) {}
    }
}
Run Code Online (Sandbox Code Playgroud)

What's an elegant solution to this problem? Is it possible to use Optional在评估期间发生异常时不存在的?如果有,怎么样?

Tun*_*aki 5

这可以使用DateTimeFormatter可选部分以优雅的方式完成.可选部分由[令牌启动,并以.结尾].

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy[-MM-dd]]");
System.out.println(formatter.parse("2012-12-12")); // prints "{},ISO resolved to 2012-12-12"
System.out.println(formatter.parse("2012")); // prints "{Year=2012},ISO"
System.out.println(formatter.parse("")); // prints "{},ISO"
Run Code Online (Sandbox Code Playgroud)