Reputation: 788
The client could be able to send either String
in format
"yyyy-MM-dd HH:mm:ss"
or "yyyy-MM-dd"
and depending on it I need to either just parse full LocalDateTime
if he sent me full format or to create LocalDateTime
object with default Time
part "23:59:59"
For now I have written this solution but it seems to be bad as I am using exceptions for controlling business logic.
public class LocalDateTimeConverter implements IStringConverter<LocalDateTime> {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public LocalDateTime convert(String value) {
LocalDateTime localDateTime;
try {
localDateTime = LocalDateTime.parse(value, DATE_TIME_FORMATTER);
} catch (DateTimeParseException ex) {
localDateTime = LocalDateTime.of(LocalDate.parse(value), LocalTime.of(23, 59, 59));
}
return localDateTime;
}
}
Any suggestions about how to implement it more clearly?
Upvotes: 2
Views: 475
Reputation: 9541
I've never worked with parseDefaulting
but a quick shot at it seems to work.
private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR_OF_ERA, 4, 4, SignStyle.NEVER)
.appendLiteral('-')
.appendValue(ChronoField.MONTH_OF_YEAR, 2, 2, SignStyle.NEVER)
.appendLiteral('-')
.appendValue(ChronoField.DAY_OF_MONTH, 2, 2, SignStyle.NEVER)
.optionalStart()
.appendLiteral(' ')
.appendValue(ChronoField.HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(ChronoField.MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(ChronoField.SECOND_OF_MINUTE, 2)
.optionalEnd()
.parseDefaulting(ChronoField.HOUR_OF_DAY, 23)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 59)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 59)
.toFormatter();
LocalDateTime.parse("2000-01-01 01:02:03", DATE_TIME_FORMATTER) // 2000-01-01T01:02:03
LocalDateTime.parse("2000-01-01", DATE_TIME_FORMATTER) // 2000-01-01T23:59:59
Upvotes: 7
Reputation: 164214
Check the length of the input string to decide which format must be applied, like this:
public LocalDateTime convert(String value) {
value = value.trim();
boolean isShort = value.length() <= 10;
DateTimeFormatter DATE_TIME_FORMATTER;
if (isShort) {
DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
} else {
DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
}
LocalDateTime localDateTime;
try {
localDateTime = LocalDateTime.parse(value, DATE_TIME_FORMATTER);
if (isShort) {
localDateTime = localDateTime.with(LocalTime.of(23, 59, 59));
}
} catch (DateTimeParseException ex) {
localDateTime = null;
}
return localDateTime;
}
Upvotes: 1