| 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
|
 |
 |
|
|
subject: sorting date in java
|
|
|