Parse Best
Description
The DateTimeFormatter class contains a parseBest() method.
parseBest() method tries to match the string with provided format with optional format symbols.
In the following pattern we have two optional patterns.
yyyy-MM-dd['T'HH:mm:ss[Z]]
A text may be fully parsed to an OffsetDateTime, and partially parsed to a LocalDateTime and a LocalDate.
Example
The following code shows how to use optional patterns to get best match date time objects from string.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
/*ww w . j ava 2 s . co m*/
public class Main {
public static void main(String[] args) {
DateTimeFormatter parser = DateTimeFormatter
.ofPattern("yyyy-MM- dd['T'HH:mm:ss[Z]]");
parseStr(parser, "2014-06-31");
parseStr(parser, "2014-06-31T15:31:12");
parseStr(parser, "2014-06-31T15:31:12-0500");
parseStr(parser, "2014-06-31Hello");
}
public static void parseStr(DateTimeFormatter formatter, String text) {
try {
TemporalAccessor ta = formatter.parseBest(text, OffsetDateTime::from,
LocalDateTime::from, LocalDate::from);
if (ta instanceof OffsetDateTime) {
OffsetDateTime odt = OffsetDateTime.from(ta);
System.out.println("OffsetDateTime: " + odt);
} else if (ta instanceof LocalDateTime) {
LocalDateTime ldt = LocalDateTime.from(ta);
System.out.println("LocalDateTime: " + ldt);
} else if (ta instanceof LocalDate) {
LocalDate ld = LocalDate.from(ta);
System.out.println("LocalDate: " + ld);
} else {
System.out.println("Parsing returned: " + ta);
}
} catch (DateTimeParseException e) {
System.out.println(e.getMessage());
}
}
}
The code above generates the following result.