我想将一些文本解析为一个日期。但是,不能保证文本具有所需的格式。这可能是2012-12-12
或者2012
甚至。
目前,我正在尝试嵌套try-catch块,但这并不是一个好方向(我想)。
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) {}
}
}
什么是解决这个问题的优雅方法?Optional
如果评估期间发生异常,是否可以使用不存在的?如果是,怎么办?
本DateTimeFormatterBuilder
类包含的积木,使这项工作:
LocalDate now = LocalDate.now();
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.appendPattern("[uuuu[-MM[-dd]]]")
.parseDefaulting(ChronoField.YEAR, now.getYear())
.parseDefaulting(ChronoField.MONTH_OF_YEAR, now.getMonthValue())
.parseDefaulting(ChronoField.DAY_OF_MONTH, now.getDayOfMonth())
.toFormatter();
System.out.println(LocalDate.parse("2015-06-30", fmt));
System.out.println(LocalDate.parse("2015-06", fmt));
System.out.println(LocalDate.parse("2015", fmt));
System.out.println(LocalDate.parse("", fmt));
该parseDefaulting()
方法允许为特定字段设置默认值。在所有情况下,LocalDate
都可以从结果中解析出a ,因为可以获得足够的信息。
还请注意在模式中使用“ [...]”部分来定义可选内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句