我有格式爲(MM/DD/YYYY)的日期字段(字符串)來自服務調用。 我的要求是按日期排序清單,並顯示最新日期的記錄。按日期排列以MM/DD/YYYY排列列表格式
我已經嘗試了下面的代碼,但我無法顯示最新日期的記錄。
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;
}
}
實際輸出:
Opportunity Date>>>11/07/2016
Opportunity Date>>>11/08/2016
預期輸出:
Opportunity Date>>>11/08/2016
Opportunity Date>>>11/07/2016
日期是一個日期,無論你如何格式化,則需要再進行比較,以便對它進行排序.. –
試使用date2調用compareTo(),並在其中傳入date1 –
我也試過這種方式。它不工作 – String