Sunday, January 22, 2006

java: Sorting Dates in a List (Collection)

final String DATE_FORMAT = "dd/MM/yy";
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
dateFormat.setTimeZone(TimeZone.getDefault());

//we store date as time in milliseconds.
//getTime() returns the number of milliseconds since
//midnight of January 1, 1970. This method is also very
//useful for generating a unique sequence of numbers.
Long date0 = new Long(dateFormat.parse("29/01/1995").getTime());
Long date1 = new Long(dateFormat.parse("13/12/2007").getTime());
Long date2 = new Long(dateFormat.parse("01/04/2000").getTime());

List dateList = new ArrayList();
dateList.add(date0);
dateList.add(date1);
dateList.add(date2);

Collections.sort(dateList);

//Get wrapper Long from list. convert Long to String. 
//Convert String to primitive long. Convert primitive long to Date.
Date dateLatest = new Date(Long.parseLong(((Long) dateList.get(dateList.size()-1)).toString()));
String dateLatestString = dateFormat.format(dateLatest);

System.out.println(dateLatestString);

No comments: