저는 장단점이있는 두 가지 옵션을 제시합니다.
하나, 당신의 세 가지 형식을 허용하도록 사용자 정의 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 형식만으로도 품질이 우수하다고 생각합니다. 3 개의 샘플 문자열에 대한 결과는 위와 같습니다.
[DateTimeFormatter] (https://docs.oracle.com/javase/8/docs/apat/java/time/format/DateTimeFormatter.html)에 대한 내용 – Jens
첫 번째 형식의 '+02 : 00' 그냥 무시해야합니까? 세 번째 시간에 0:00 (자정)이라고 가정합니까? –
@ OleV.V. 예, 예. –