I think you have a question in reverse order. You do not want to determine if the formatter uses only date or date / time. You create a formatter based on what you need to parse and on what you intend to store the result. Obviously, if you create a formatter that does not handle the temporary part, using it for analysis in LocalDateTime is a misconception.
If you need to parse dates that may appear with two formats, such as "yyyy-MM-dd" or "yyyy-MM-dd HH:mm:ss" (with the time part), it is not parsed to determine what he should do, but up to the format to provide a default in case there is no time.
With Java Time, this is done with additional sections and default values. For example, the pattern "yyyy-MM-dd[ HH:mm:ss]" will be able to parse a String date (for example, "2016-01-11" ) and a String date / time (for example, "2016-01-11 20:10:10" ). If you store this value in LocalDateTime , you will need to specify default values ββif there is no time component. This is done using parseDefaulting(field, value) : this will say that formatting will return the default value for this chrono field, if it is not already set.
The following code creates such a formatter and by default sets the time until midnight.
public static void main(String[] args) { DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd[ HH:mm:ss]") .parseDefaulting(ChronoField.HOUR_OF_DAY, 0) .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0) .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0) .toFormatter(); LocalDateTime dt1 = LocalDateTime.parse("2016-01-11", formatter); LocalDateTime dt2 = LocalDateTime.parse("2016-01-11 20:10:10", formatter); }
Of course, this logic can only be extended for parsing only String and by default for the date component to the current date.
source share