我正在为一些验证用户出生日期的遗留代码编写一些测试。我在课堂上遇到了以下方法。我怀疑try块中的if语句是否必要。根据我的理解,如果 parse 函数成功返回一个 LocalDate 对象,那么 date.toString() 应该总是等于输入的 dobstr,并且不需要做额外的检查。我错过了什么吗?我想不出任何我们需要额外检查的情况。请帮忙。谢谢!
private LocalDate format(String dobStr) throws Exception {
LocalDate date = null;
try {
date = LocalDate.parse(dobStr, DateTimeFormatter.ISO_DATE);
if (!dobStr.equals(date.toString())) {
throw new DateTimeParseException("some message");
}
}
catch (DateTimeParseException ex) {
throw ex;
}
return date;
}
Run Code Online (Sandbox Code Playgroud)
这是我在 DateTimeFormatter.ISO_DATE 的源代码中找到的
public static final DateTimeFormatter ISO_DATE;
static {
ISO_DATE = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(ISO_LOCAL_DATE)
.optionalStart()
.appendOffsetId()
.toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
}
Run Code Online (Sandbox Code Playgroud)