Hey guys, back again I be. Having a new problem with my dates. I want to sort by date and that's fine but in order to sort correctly by date i would have to reverse the date and ignore the slashes or it wont recognise that 2006 is before 2007 for instance as it only reads the first bit. Is there something i can do to reverse this string for sorting.

Regards
Jez

Recommended Answers

All 2 Replies

Well, sort date objects rather than date strings and you wn't have this problem. Use SimpleDateFormat to create actual date objects from the date strings, then sort those.

Parsing them into valid dates as masijade mentioned is really best, but if you have simple date strings like "12/01/2006", you could use the String split() function to put them in year-month-day form "20031201" for integer sorting

String date = "12/10/2006";
String[] datePieces = date.split("/");
String rebuiltDate = datePieces[2]+datePieces[0]+datePieces[1];
System.out.println(rebuiltDate);

If you have times in the string as well then it gets trickier and you would need to use regex parsing to create the sortable representation - at which point you would have just been better off using the date formatter in the first place...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.