Is there a way to have a column in the TableView show a proper date instead of:
java.util.GregorianCalendar[time=?areFieldsSet=false...
I want to know because it's irritating having it displayed like that on the Date column I have and having to switch between Date and GregorianCalendar get's messy and annoying.
First, I would strongly recommend using the java.time
API, instead of legacy classes such as java.util.Calendar
and java.util.Date
, etc.
In any case, you can change how data in cells in a given column are displayed by using a cell factory on the column. In the case where your cell value factory is generating Calendar
instances, you presumably have
TableColumn<MyTableType, Calendar> dateColumn ;
// ...
dateColumn.setCellValueFactory(...);
You can additionally do
DateFormat dateFormat = DateFormat.getDateInstance();
dateColumn.setCellFactory(col -> new TableCell<MyTableType, Calendar>() {
@Override
protected void updateItem(Calendar date, boolean empty) {
super.updateItem(date, empty);
if (empty) {
setText(null);
} else {
setText(dateFormat.format(date.getTime()));
}
}
});
If you use the aforementioned java.time
API, you represent a date with LocalDate
and use a DateTimeFormatter
to do the formatting:
TableColumn<MyTableType, LocalDate> dateColumn ;
// ...
dateColumn.setCellValueFactory(...);
DateTimeFormatter dateFormat = DateTimeFormatter.ISO_LOCAL_DATE;
dateColumn.setCellFactory(col -> new TableCell<MyTableType, LocalDate>() {
@Override
protected void updateItem(LocalDate date, boolean empty) {
super.updateItem(date, empty);
if (empty) {
setText(null);
} else {
setText(dateFormat.format(date));
}
}
});