File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Sorting Jtables with dates Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Sorting Jtables with dates" Watch "Sorting Jtables with dates" New topic

Sorting Jtables with dates

Cy Bird

Joined: Feb 18, 2003
Posts: 16
I have a column in a JTable that holds a date value in mm/dd/yyyy format. The actual value in the database is a java.util.Date, but we convert it to a string using a SimpleDateFormat to get it into the mm/dd/yyyy format.
In string form though, it doesn't sort correctly: 11/10/2003 comes before 11/11/2002. When I leave it a date, it sorts correctly, but displays in the wrong format: MMM dd, yyyy.
Does anyone know a way around this?
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

Store it as a Date and use a cell renderer to display it as a String in the format you want.

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Cy Bird

Joined: Feb 18, 2003
Posts: 16
Yes, thank you. I found my way there...
For anyone else with this problem, I ended up with something like this:
getTableCellRendererComponent() {
SimpleDateFormat dateFormat_mmddyy = new SimpleDateFormat("MM-dd-yyyy");
String formatted = dateFormat_mmddyy.format((Date)value);
return new JLabel(formatted);
I agree. Here's the link:
subject: Sorting Jtables with dates
jQuery in Action, 3rd edition