user4919196
user4919196

Reputation: 81

JavaFX: bind LocalDateProperty to StringProperty with custom Formatter

I want to bind a ObjectProperty<LocalDate> to a TextField and format the date according to the current locale or a custom Formatter.

At the moment I use

myTextfield.textProperty().bind(myObject.myDateProperty().asString());

this produces a string in ISO 8601 format (YYYY-MM-DD). How to get e.g. DD.MM.YYYY?

Upvotes: 2

Views: 3167

Answers (2)

user4919196
user4919196

Reputation: 81

Ok, found a simple solution (using Bindings.createStringBinding):

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy");
myTextfield.textProperty().bind(Bindings.createStringBinding(() ->
    dtf.format(myObject.myDateProperty().get()), myObject.myDateProperty())
);

Upvotes: 6

Puce
Puce

Reputation: 38132

I recommend a different approach: use a DatePicker instead of a TextField directly.

You then can use the converter property, if the default formatting doesn't fit your needs.

Upvotes: 0

Related Questions