Converts the input text to an object of type LocalDate and vice versa.
If not set by the application, the DatePicker skin class will
set a converter based on a java.time.format.DateTimeFormatter
for the current java.util.Locale and
chronology. This formatter is
then used to parse and display the current date value.
Setting the value to null will restore the default
converter.
Example using an explicit formatter:
datePicker.setConverter(new StringConverter<LocalDate>() {
String pattern = "yyyy-MM-dd";
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);
{
datePicker.setPromptText(pattern.toLowerCase());
}
@Override public String toString(LocalDate date) {
if (date != null) {
return dateFormatter.format(date);
} else {
return "";
}
}
@Override public LocalDate fromString(String string) {
if (string != null && !string.isEmpty()) {
return LocalDate.parse(string, dateFormatter);
} else {
return null;
}
}
});
Example that wraps the default formatter and catches parse exceptions:
final StringConverter<LocalDate> defaultConverter = datePicker.getConverter();
datePicker.setConverter(new StringConverter<LocalDate>() {
@Override public String toString(LocalDate value) {
return defaultConverter.toString(value);
}
@Override public LocalDate fromString(String text) {
try {
return defaultConverter.fromString(text);
} catch (DateTimeParseException ex) {
System.err.println("HelloDatePicker: "+ex.getMessage());
throw ex;
}
}
});
The default base year for parsing input containing only two digits for
the year is 2000 (see java.time.format.DateTimeFormatter). This
default is not useful for allowing a person's date of birth to be typed.
The following example modifies the converter's fromString() method to
allow a two digit year for birth dates up to 99 years in the past.
@Override public LocalDate fromString(String text) {
if (text != null && !text.isEmpty()) {
Locale locale = Locale.getDefault(Locale.Category.FORMAT);
Chronology chrono = datePicker.getChronology();
String pattern =
DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT,
null, chrono, locale);
String prePattern = pattern.substring(0, pattern.indexOf("y"));
String postPattern = pattern.substring(pattern.lastIndexOf("y")+1);
int baseYear = LocalDate.now().getYear() - 99;
DateTimeFormatter df = new DateTimeFormatterBuilder()
.parseLenient()
.appendPattern(prePattern)
.appendValueReduced(ChronoField.YEAR, 2, 2, baseYear)
.appendPattern(postPattern)
.toFormatter();
return LocalDate.from(chrono.date(df.parse(text)));
} else {
return null;
}
}
Diagram: Choice, Combo