我提出了兩個選項,每個選項都有其優點和缺點。
一,建立一個自定義DateTimeFormatter
接受你的三種可能的形式:
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);
}
一方面,它的清潔,另一方面,有人可以很容易地找到它有點棘手。對於你的問題三個樣本串它產生:
2017-04-30T00:00
2016-12-05T04:00
2016-12-05T00:00
另一種選擇,嘗試了三種不同的格式轉,挑選的作品之一:
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格式是有質量的。你的三個示例字符串的結果與上面相同。
閱讀[DateTimeFormatter](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) – Jens
因此,第一種格式的「+02:00」應該被忽略?你在第三個假設時間是0點(午夜)嗎? –
@ OleV.V。是的,是的。 –