2015-04-07 8 views
8

Sto usando questo DateTimeFormatter:di analisi di data locale non utilizza desiderato secolo

DateTimeFormatter.ofPattern("ddMMYY") 

voglio analizzare la stringa 150790 ed ho ottenuto questo errore:

Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=15, MonthOfYear=7, WeekBasedYear[WeekFields[MONDAY,4]]=2090},ISO of type java.time.format.Parsed 

Ovviamente, vogliono ottenere le seguenti TemporalAccessor:

{DayOfMonth=15, MonthOfYear=7, WeekBasedYear=1990} 

sai perché ho avuto l'anno 209 0 invece del 1990?

Grazie per il vostro aiuto

risposta

12

Dal momento che questa domanda è davvero di nuovo java.time -package e NON SimpleDateFormat Citerò seguenti relevant section:

Year: The count of letters determines the minimum field width below which padding is used. If the count of letters is two, then a reduced two digit form is used. For printing, this outputs the rightmost two digits. For parsing, this will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.

Vediamo che Java-8 utilizza la gamma 2000- 2099 per default, non come SimpleDateFormat intervallo -80 anni fino a +20 anni rispetto ad oggi.

Se si desidera configurarlo, è necessario utilizzare appendValueReduced(). Questo è stato progettato in modo scomodo, ma possibile, vedere qui:

String s = "150790"; 

// old code with base range 2000-2099 
DateTimeFormatter dtf1 = 
    new DateTimeFormatterBuilder().appendPattern("ddMMyy").toFormatter(); 
System.out.println(dtf1.parse(s)); // 2090-07-15 

// improved code with base range 1935-2034 
DateTimeFormatter dtf2 = 
    new DateTimeFormatterBuilder().appendPattern("ddMM") 
    .appendValueReduced(
    ChronoField.YEAR, 2, 2, Year.now().getValue() - 80 
).toFormatter(); 
System.out.println(dtf2.parse(s)); // 1990-07-15 

A proposito, se si vuole veramente anni settimana a base di allora bisogna usare Y al posto di y o il campo appropriato IsoFields.WEEK_BASED_YEAR. Per quanto riguarda il fatto che non ci sono altri campi relativi alla settimana, vorrei assumere il normale anno solare, non quello settimanale.

Problemi correlati