aspose file tools
The moose likes Java in General and the fly likes sorting date in java Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "sorting date in java" Watch "sorting date in java" New topic
Author

sorting date in java

Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
hi all
I am having a list containing set of string objects in the below format
"YYYY-MM-DD".

My requirement is i need to sort these objects (after converting String to Date). so how can i do the following

1) Creating date object from the given string
2) Comparing dates - sort it in ascending order.
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
In order to create a java.util.Date object from the given java.lang.String use java.util.DateFormat or java.util.SimpleDateFormat.

In order to comparing dates you can use the compareTo() method in the java.util.Date class.

In order to sort the dates in a java.util.List use the java.util.Collections class which has sort() method.

If you have special needs to sort the list you can also create you own java.util.Comparator and usit in the sort() method to set some orde in the java.util.List.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18670
I would note that with a YYYY-MM-DD format, sorting the date is equivalent to an alphanumeric sort. That is, the result you get from String's compareTo() method is the same as what you'd get if you converted the Strings to Dates and used Date's compareTo() method. So you can keep things simple here by not using Dates at all. Just use a java.util.List (probably ArrayList) containing all your Strings, and then use java.util.Collections.sort().


"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: sorting date in java
 
Similar Threads
Treemap key sort
How can I sort an array of strings, but not by 1st character?
Sorting custom objects with Java collections
sorting a 2d arraylist
Sorting in Java