Skip to content
Advertisement

How to sort dates of type string in java

I am building a android project where am storing some details which includes date as string,but now I need to sort the list view by date.I am bit confused on how to do it.I am done with everything but need to sort the list by date.

Here is the overview of how am storing data.

I have an arraylist of type Person like

ArrayList<Person> personDetails = new ArrayList<Person>();

Person class consists of several variable but I will limit to three 1)name 2)Record created(date) 3)Address

then add to Person like personDetails.add(Person Object).

Please guide me on how to sort the list by date.

Thanks for your time.

Advertisement

Answer

Implement Comparable in your Person class:

public class Person implements Comparable<Person> {

    public int compareTo(Person person) {
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
        return sdf.parse(this.dateString).compareTo(sdf.parse(person.dateString));
    }
}

Replace "YYYY-MM-dd" with the format of your date string.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement