2016-03-18 14 views
5

voglio analizzare un LocalDateTime dal seguente schema:LocalDateTime.parse() con un modello solo numeri

yyyyMMddHHmmss000000 

Ciò significa che il solito "yyyy ... ss" e poi a sei zeri finali.

Quindi, la formattazione funziona bene:

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

e ma 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 

L'eccezione:

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) 
... 

Non posso cambiare il formato del valore di ingresso. Come posso analizzarlo correttamente? Il mio modello è sbagliato?

Java Version: 1.8.0_60 su OSX

+1

Per ragioni di completezza, il bug: https://bugs.openjdk.java.net/browse/JDK-8031085 – Marcel

risposta

7

Questo appare come si tratta di un bug con DateTimeFormatter e la sua gestione della larghezza variabile di ingresso.

Costruire il seguente formattatore con DateTimeFormatterBuilder risolve il problema

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

La differenza è che obbliga una larghezza per il campo da analizzare con appendValue(field, width).

Questo errore sembra simile a quello menzionato in another answer of mine sebbene menzioni millisecondi invece di caratteri letterali nel modello.

+1

L'unico lato negativo è che si sta introducendo un problema Y10K :) – bowmore

+2

@bowmore corretta: D Facciamo spero che il bug sarà risolto :) – Tunaki

Problemi correlati