Parse date - just like LocalDateTime in Java 8

I need to analyze a field, which is sometimes indicated as a date, and sometimes as a date / time. Is it possible to use one data type for this using the Java 8 time API? Currently, I tried using LocalDateTime for it, but for a subsequent call, LocalDateTime.parse("1986-04-08", DateTimeFormatter.ofPattern("yyyy-MM-dd")) I get

java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 1986-04-08 of type java.time.format.Parsed

This is part of some common parser that accepts a date / date and time analysis pattern as a configuration parameter. For example, the following solution with a hard-coded analysis pattern

if ("yyyy-MM-dd".equals(pattern)) {
    LocalDate.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd"))).atStartOfDay()
}

not an option for me.

Any other suggestions on how to code it in your own way are welcome.

+2
source share
2 answers

builder DateTimeFormatterBuilder

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();

[], , HOUR_OF_DAY, MINUTE_OF_HOUR SECOND_OF_MINUTE.

: , , .

.

LocalDateTime localDateTime1 = LocalDateTime.parse("1994-05-13", formatter);
LocalDateTime localDateTime2 = LocalDateTime.parse("1994-05-13 23:00:00", formatter);

0 ( ).

System.out.println(localDateTime1); // 1994-05-13T00:00
System.out.println(localDateTime2); // 1994-05-13T23:00
+4

parseDefaulting . , DateTimeFormatterBuilder.

- , []:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd[ HH:mm:ss]");

parseBest, String :

TemporalAccessor parsed = fmt.parseBest("1986-04-08", LocalDateTime::from, LocalDate::from);

LocalDateTime, , LocalDate ( , ).

, , :

LocalDateTime dt;
if (parsed instanceof LocalDateTime) {
    // it a LocalDateTime, just assign it
    dt = (LocalDateTime) parsed;
} else if (parsed instanceof LocalDate) {
    // it a LocalDate, set the time to whatever you want
    dt = ((LocalDate) parsed).atTime(LocalTime.MIDNIGHT);
}

LocalDate, atStartOfDay(), , , atTime(LocalTime.of(10, 30)) 10:30 , .

+2

Source: https://habr.com/ru/post/1695044/


All Articles