Wednesday, July 04, 2007

Java: Sorting Dates

Had someone ask a simple question in a forum today. They wanted to be able to sort dates in Java. The simple answer is that if you use any of the standard Java collections, you can use the Collection.sort method to do the sort. Or you could use a TreeSet... Below is an example.

package dateSort;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;

public class DateSort {
public static void main(String[] args) {
ArrayList dates = new ArrayList();
DateFormat parser = DateFormat.getDateInstance();

try {
dates.add(new Date());
dates.add(parser.parse("Jan 01, 2005"));
dates.add(parser.parse("Jan 01, 2003"));
} catch (ParseException e) {
e.printStackTrace();
}

for (Iterator i = dates.iterator(); i.hasNext();)
{
Date currentDate = (Date) i.next();
System.out.println(currentDate);
}

Collections.sort(dates);
System.out.println("After Sort:------------------");
for (Iterator i = dates.iterator(); i.hasNext();)
{
Date currentDate = (Date) i.next();
System.out.println(currentDate);
}
}
}


No comments: