purring pigeon
purring pigeon

Reputation: 4209

How to use custom date format for a DatePicker

Is there a way to configure a DatePicker to accept a custom format in addition to the currently supported formats?

For example - instead of the user typing "04/06/2016" into the field, they could enter "04062016" or "04.06.2016"?

Currently I can see that the acceptable separators are a "/" and a "-".

Thanks!

Upvotes: 2

Views: 3300

Answers (2)

Gravity Grave
Gravity Grave

Reputation: 2862

There's an even more clear example in the docs here now.

Upvotes: 0

José Pereda
José Pereda

Reputation: 45486

You can define as many patterns as you want, and in your Converter check if the entered date fits any of them.

private final List<String> patterns = Arrays.asList(
        "MM/dd/yyyy", "MMddyyyy", "MM.dd.yyyy");

@Override
public void start(Stage stage) {
    DatePicker datePicker = new DatePicker();
    datePicker.setConverter(new StringConverter<LocalDate>() {
        @Override
        public String toString(LocalDate date) {
            if (date != null) {
                for (String pattern : patterns) {
                    try {
                        return DateTimeFormatter.ofPattern(pattern).format(date);
                    } catch (DateTimeException dte) { }
                }
                System.out.println("Format Error");
            } 
            return "";
        }
        @Override
        public LocalDate fromString(String string) {
            if (string != null && !string.isEmpty()) {
                for (String pattern : patterns) {
                    try {
                        return LocalDate.parse(string, DateTimeFormatter.ofPattern(pattern));
                    } catch (DateTimeParseException dtpe) { }
                }
                System.out.println("Parse Error");
            }
            return null;
        }
    });
}

Upvotes: 4

Related Questions