LocalDateTime.parse () с форматом без часов, минут и т. Д. - PullRequest
0 голосов
/ 29 апреля 2019

Я хочу проанализировать строку даты и времени в LocalDateTime.Формат ввода может не содержать часов, минут и т. Д.Например, это может быть «гггг М д».Учитывая этот шаблон, вы можете анализировать строку в LocalDate, но не в LocalDateTime.Я хочу создать LocalDateTime.

Существует способ сделать это с DateTimeFormatterBuilder, как показано ниже.

// this code works. But I don't want to use DateTimeFormatterBuilder
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern("yyyy")
                .appendLiteral('-')
                .appendValue(MONTH_OF_YEAR)
                .appendLiteral('-')
                .appendValue(DAY_OF_MONTH)
                .parseDefaulting(HOUR_OF_DAY, 12)
                .parseDefaulting(MINUTE_OF_HOUR, 13)
                .parseDefaulting(SECOND_OF_MINUTE, 14)
                .toFormatter();
        System.out.println(LocalDateTime.parse("2015-09-05", formatter));

Но я хочу использовать DateTimeFormatter.ofPattern () вместо DateTimeFormatterBuilder.Но я не знаю, как заставить работать приведенный ниже код:

// this code doesn't work.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
        System.out.println(LocalDateTime.parse("2015-09-05", formatter));

Выдает исключение

Exception in thread "main" java.time.format.DateTimeParseException: Text '2015-09-05' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2015-09-05 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
...
...