Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Date Picker time format

I have this example of Date Picker. Can you tell me how I can set the date format of the calendar?

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.DatePicker;
import javafx.stage.Stage;

import java.time.LocalDate;

public class PickerDemo extends Application {
    @Override public void start(Stage stage) {
        final DatePicker datePicker = new DatePicker(LocalDate.now());
        datePicker.setOnAction(event -> {
            LocalDate date = datePicker.getValue();
            System.out.println("Selected date: " + date);
        });

        stage.setScene(
            new Scene(datePicker)
        );
        stage.show();
    }
    public static void main(String[] args) { launch(args); }
}
like image 987
Peter Penzov Avatar asked Dec 04 '13 19:12

Peter Penzov


1 Answers

This should do the trick:

datePicker.setConverter(new StringConverter<LocalDate>()
{
    private DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("dd/MM/yyyy");

    @Override
    public String toString(LocalDate localDate)
    {
        if(localDate==null)
            return "";
        return dateTimeFormatter.format(localDate);
    }

    @Override
    public LocalDate fromString(String dateString)
    {
        if(dateString==null || dateString.trim().isEmpty())
        {
            return null;
        }
        return LocalDate.parse(dateString,dateTimeFormatter);
    }
});
like image 147
Thunder Avatar answered Oct 05 '22 23:10

Thunder