更新时间:2021-08-17 00:49:04
我提出了两个选项,每个选项都有其优缺点.
I am presenting two options, each with its pros and cons.
一,构建自定义DateTimeFormatter
以接受您的三种可能的格式:
One, build a custom DateTimeFormatter
to accept your three possible formats:
public static LocalDateTime parse(String dateFromJson) {
DateTimeFormatter format = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE)
.optionalStart()
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.optionalStart()
.appendOffsetId()
.optionalEnd()
.optionalEnd()
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter();
return LocalDateTime.parse(dateFromJson, format);
}
一方面,它很干净,另一方面,有人很容易发现它有点棘手.对于您问题中的三个示例字符串,它会生成:
On one hand, it’s clean, on the other, someone could easily find it a bit tricky. For the three sample strings in your question it produces:
2017-04-30T00:00
2016-12-05T04:00
2016-12-05T00:00
另一种选择,依次尝试三种不同的格式,然后选择一种有效的格式:
The other option, try the three different formats in turn and pick the one that works:
public static LocalDateTime parse(String dateFromJson) {
try {
return LocalDateTime.parse(dateFromJson);
} catch (DateTimeParseException e) {
// ignore, try next format
}
try {
return LocalDateTime.parse(dateFromJson, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
} catch (DateTimeParseException e) {
// ignore, try next format
}
return LocalDate.parse(dateFromJson).atStartOfDay();
}
我不认为这是最漂亮的代码,还是有人认为它比第一个选项更直接?我认为仅依赖内置的 ISO 格式是有好处的.三个示例字符串的结果与上述相同.
I don’t consider this the most beautiful code, still some may think it’s more straightforward than the first option? I think there’s a quality in relying on the built-in ISO formats alone. The results for your three sample strings are the same as above.