DatePicker
A DatePicker lets the user choose a date from a calendar. It returns a LocalDate object.
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.DatePicker?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox spacing="15"
alignment="CENTER"
xmlns="http://javafx.com/javafx/17"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="org.example.demo.HelloController">
<Label text="Choose your birth date:"/>
<DatePicker fx:id="birthDatePicker"
onAction="#handleDateSelection"/>
<Button text="Show Information"
onAction="#showDateInformation"/>
<Label fx:id="resultLabel"
text="No date selected yet."/>
</VBox>
Controller
package org.example.demo;
import javafx.fxml.FXML;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public class HelloController {
@FXML
private DatePicker birthDatePicker;
@FXML
private Label resultLabel;
private final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("dd / MM / yyyy");
@FXML
private void initialize() {
// Set a default date
birthDatePicker.setValue(LocalDate.of(2000, 1, 1));
resultLabel.setText(
"Default date: " + formatter.format(birthDatePicker.getValue())
);
}
@FXML
private void handleDateSelection() {
LocalDate selectedDate = birthDatePicker.getValue();
if (selectedDate != null) {
resultLabel.setText(
"Selected date: " + formatter.format(selectedDate)
);
}
}
@FXML
private void showDateInformation() {
LocalDate selectedDate = birthDatePicker.getValue();
if (selectedDate == null) {
resultLabel.setText("Please select a date first.");
return;
}
// Calculate age
LocalDate today = LocalDate.now();
Period age = Period.between(selectedDate, today);
resultLabel.setText(
"You selected " + formatter.format(selectedDate)
+ "\nAge: " + age.getYears() + " years"
+ "\nMonth: " + selectedDate.getMonth()
);
}
}
Example of what happens
If the user selects:
15 / 08 / 2010
The label changes to:
Selected date: 15 / 08 / 2010
Then after clicking the button:
You selected 15 / 08 / 2010
Age: 15 years
Month: AUGUST
Important methods
birthDatePicker.getValue(); // Get selected date
birthDatePicker.setValue(LocalDate.now()); // Set today's date
birthDatePicker.setDisable(true); // Disable the control
birthDatePicker.setEditable(false); // Prevent typing manually
More advanced example: prevent future dates
You can stop the user from choosing a future date:
birthDatePicker.setDayCellFactory(picker -> new DateCell() {
@Override
public void updateItem(LocalDate date, boolean empty) {
super.updateItem(date, empty);
if (date.isAfter(LocalDate.now())) {
setDisable(true);
setStyle("-fx-background-color: #ffc0cb;");
}
}
});
This disables all dates after today and colors them pink.