String String - 25 days ago 7
Java Question

Sorting arraylist by date in MM/DD/YYYY Format

I have Date Field(String) with format (MM/DD/YYYY) comes from Service call.
My requirement is sort the list by date and display records by Latest date.

I have tried the below code.But I am not able to display records by latest date.

public class Test {

public static void main(String[] args) {
List<Opportunity> oppList = new ArrayList<Opportunity>();
Opportunity opp1 = new Opportunity();
opp1.setName("opp1");
opp1.setExpires("11/07/2016");
Opportunity opp2 = new Opportunity();
opp2.setName("opp2");
opp2.setExpires("11/08/2016");
oppList.add(opp1);
oppList.add(opp2);
List<Opportunity> opplist=sortOpportunitiesByDate(oppList);
/*Collections.sort(oppList);*/
for(int i=0; i<opplist.size(); i++){
System.out.println("Opportunity Data>>>"+opplist.get(i).getExpires());

}

}
private static List<Opportunity> sortOpportunitiesByDate(List<Opportunity> opportunities) {
Collections.sort(opportunities, new Comparator<Opportunity>() {
public int compare(Opportunity o1, Opportunity o2) {
DateFormat format = new SimpleDateFormat("MM/DD/YYYY",Locale.US);

Date date1 = null;
Date date2 = null;
try {
date1=format.parse(o1.getExpires());
date2=format.parse(o2.getExpires());

} catch (ParseException e) {
e.printStackTrace();
}

return date1.compareTo(date2);
}
});

return opportunities;
}


}


Actual Output:

Opportunity Date>>>11/07/2016
Opportunity Date>>>11/08/2016


Expected Output:

Opportunity Date>>>11/08/2016
Opportunity Date>>>11/07/2016

Answer

Because format "YYYY" in your DateFormat Change MM/DD/YYYY to MM/DD/yyyy will work