更新时间:2021-08-17 00:48:22
我提出了两种选择,每种选择都有其优缺点。
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.