问题
I'm writing an application to manipulate text data, Which will change the content of input string and create new output String based on the format of input string.
I encounter some problem with recognized the date time string. Based on the document the input date time may have some optional section, here the sample pattern:
yyyy[MM[dd[HHmm]]][Z]
So after some digging on the web, my first attempt to use the parseBest function.
public boolean checkFormatDate(string input){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy[MM[dd[HHmm]]][Z]");
try {
TemporalAccessor temporalAccessor = formatter.parseBest(input, ZonedDateTime::from, LocalDateTime::from, LocalDate::from);
return true;
} catch (Exception e) {
return false;
}
}
But the code above failed with these case:
1900 190001 190001011440
My suspect is that the queries that parse the parseBest method is not correct. Can someone help me with this.
Edit:
Here is the exception log:
java.time.format.DateTimeParseException: Text '190001011440' could not be parsed at index 0 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947) at java.time.format.DateTimeFormatter.parseBest(DateTimeFormatter.java:1895)
回答1:
The problem seems to be the pattern yyyy
, which is creating a formatter as follows (System.out.println(formatter)
):
Value(YearOfEra,4,19,EXCEEDS_PAD)[Value(MonthOfYear,2)[Value(DayOfMonth,2)[Value(HourOfDay,2)Value(MinuteOfHour,2)]]][Offset(+HHMM,'+0000')]
Note the 4,19 in the first part - minimum width of 4 and max of 19. Build the formatter as follows and it should work:
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder();
formatter = b.appendValue(ChronoField.YEAR_OF_ERA, 4, 4, SignStyle.EXCEEDS_PAD).appendPattern("[MM[dd[HHmm]]][Z]").toFormatter();
来源:https://stackoverflow.com/questions/31645243/datetimeformater-with-optional-section