Click here to Skip to main content
15,900,815 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have an arrayList.
This is an arrayList of strings. The string contains a "Date.toString" in format of "January 1, 1970, 00:00:00 GMT" + task name.
For example: "January 1, 1970, 00:00:00 GMT clean the house".
I want to sort this arrayList by dates.
How can I do it?

Thanks
Posted
Updated 19-May-11 3:59am
v2

You'll have to convert the date part of the string to a real DateTime struct. Sorting strings isn't going to help you here. Implement a class that holds your string as well as the converted DateTime and make it implement the Comparable interface. This way you can put them in to a ArrayList instance named say myList and they'll be sorted for you by calling Collections.sort(myList).

Cheers!

-MRB
 
Share this answer
 
v2
Comments
user_code 19-May-11 11:38am    
Thanks.
But how do i convert a Date at format of "January 1, 1970, 00:00:00 GMT" to Date type?
Thanks
This list contains Strings - nothing more.

you need to extract the wanted substring(s!) [^]and sort the list by rating them. This can be done with a fuzzy logic of if/else or switch commands.

Bubble sort @ leepoint.net
[^]

Selection Sort @ leepoint.net[^]

Have fun - and when you've written some code and get stuck - come back and ask specific. We do help - but we also want you to do the homework yourself.

regards
Torsten
 
Share this answer
 
Load your string into a Comparable object:
Java
class Task implements Comparable<Task> {
    private Date date;
    private String task;
    Task (String taskString) {
        // find the split point
        int splitPoint = 45;
        try {
            this.date =
                    DateFormat.getInstance().
                    parse(taskString.substring(0, splitPoint));
        } catch (ParseException ex) {
            this.date = new Date();
        }
        this.task = taskString.substring(splitPoint);
    }
    public int compareTo(Task o) {
        int compare = this.date.compareTo(o.date);
        if (compare == 0) {
            compare = this.task.compareTo(o.task);
        }
        return compare;
    }
}


Then put this into a ArrayList. These are ordered using Collections.sort.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900