设置日期选择器时间格式

时间:2013-12-04 19:07:37

标签: javafx javafx-8

我有这个日期选择器的例子。你能告诉我如何设置日历的日期格式吗?

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); }
}

1 个答案:

答案 0 :(得分:19)

这应该可以解决问题:

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);
    }
});