How to create a default ZonedDateTime before midnight if HH: mm: ss is not defined?
Here's what I'm trying to do:
public ZonedDateTime getZdt(String myDate, String format) {
return ZonedDateTime.parse(
myDate,
DateTimeFormatter.ofPattern(format)
.withZone(ZoneId.systemDefault())
);
}
getZdt("17-05-2017 00:10:59", "dd-MM-yyyy HH:mm:ss") //works fine
getZdt("17-05-2017", "dd-MM-yyyy") //DateTimeParseException (...Unable to obtain LocalTime from TemporalAccessor:)
What I am trying to do is pretty simple. How do I get this to work?
One possibility is to change your method to the following:
public ZonedDateTime getZdt(String myDate, String format) {
try {
return ZonedDateTime.parse(myDate, DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault()));
} catch (DateTimeException e) {
return ZonedDateTime.parse(myDate + " 00:00:00", DateTimeFormatter.ofPattern(format + " HH:mm:ss").withZone(ZoneId.systemDefault()));
}
}
This assumes that a DateTimeException
will only be thrown out if format
not enough. However, I think you would be better off doing you Exception
in this case, but it will work.
I would like to see if anyone has an easier way to handle this.
You need to parse first LocalDate
, then you can convert it to ZonedDateTime
:
LocalDate.parse("17-05-2017", DateTimeFormatter.ofPattern("dd-MM-yyyy"))
.atStartOfDay(ZoneId.systemDefault())
I have three suggestions for you.
First, should there be the same method? Do you have two? I am assuming you only have two possible formats; if you have ten of them, that's a different story I think about.
/** gets a ZonedDateTime from a date string with no time information */
public ZonedDateTime getZdtFromDateString(String myDate, String format) {
return LocalDate.parse(myDate, DateTimeFormatter.ofPattern(format))
.atStartOfDay(ZoneId.systemDefault());
}
You can of course leave the parameter format
and have the format constant.
Of course, you can get what you want from a single method. Instead of passing the format to the method, I suggest that your method detects it on its own.
One option is a custom DateTimeFormatter
one that handles both formats:
private static final DateTimeFormatter format = new DateTimeFormatterBuilder().appendPattern("dd-MM-uuuu")
.optionalStart()
.appendPattern(" HH:mm:ss")
.optionalEnd()
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter();
public ZonedDateTime getZdt(String myDate) {
return LocalDateTime.parse(myDate, format).atZone(ZoneId.systemDefault());
}
Finally, Jacob G.'s idea of ββtrying both is not so bad. Here's my version:
public ZonedDateTime getZdt(String myDate, String format) {
try {
return LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern(format))
.atZone(ZoneId.systemDefault());
} catch (DateTimeParseException dtpe) {
return LocalDate.parse(myDate, DateTimeFormatter.ofPattern(format))
.atStartOfDay(ZoneId.systemDefault());
}
}
Again, you might prefer to leave the parameter format
and use the two constant formats.