LocalDateTime.parse () with only pattern numbers

I want to parse LocalDateTime from the following template:

yyyyMMddHHmmss000000 

This means the usual "yyyy ... ss", followed by six trailing zeros.

So formatting works fine:

 String p = "yyyyMMddHHmmss'000000'"; LocalDateTime.now().format(DateTimeFormatter.ofPattern(p)); 

but parsing:

 String p, v; p = "yyyyMMddHHmmss"; // without '000000' v = "20160131235930"; LocalDateTime.parse(v, DateTimeFormatter.ofPattern(p)); // it works p = "yyyy-MMddHHmmss'000000'"; // with '-' in between v = "2016-0131235930000000"; LocalDateTime.parse(v, DateTimeFormatter.ofPattern(p)); // it works p = "yyyyMMddHHmmss'000000'"; // with '000000' but without '-' v = "20160131235930000000"; LocalDateTime.parse(v, DateTimeFormatter.ofPattern(p)); // it throws Exception 

An exception:

 java.time.format.DateTimeParseException: Text '20160131235930000000' could not be parsed at index 0 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849) at java.time.LocalDateTime.parse(LocalDateTime.java:492) ... 

I cannot change the format of the input value. How can I parse it correctly? Is my template wrong?

Java Version: 1.8.0_60 on OSX

+5
source share
1 answer

It seems like this is an error with DateTimeFormatter and its handling of variable width input.

Building the next formatter with DateTimeFormatterBuilder solves the problem

 DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4) .appendValue(ChronoField.MONTH_OF_YEAR, 2) .appendValue(ChronoField.DAY_OF_MONTH, 2) .appendValue(ChronoField.HOUR_OF_DAY, 2) .appendValue(ChronoField.MINUTE_OF_HOUR, 2) .appendValue(ChronoField.SECOND_OF_MINUTE, 2) .appendLiteral("000000") .toFormatter(); 

The difference is that it forces the width of the field to be analyzed using appendValue(field, width) .

This error is similar to the one mentioned in another answer of mine , although it mentions milliseconds instead of alphabetic characters.

+7
source

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


All Articles