Reputation: 486
I am currently working on some code that requires a comparison of dates as follows:
public int compare(ItemLocation o1, ItemLocation o2) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date date1 = sdf.parse(o1.getDatePublished());
Date date2 = sdf.parse(o2.getDatePublished());
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if(cal1.equals(cal2)) {
return 0;
} else if(cal1.before(cal2)) {
return -1;
} else if(cal1.after(cal2)) {
return 1;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
So my question is muti-part.
Thanks guys!
Upvotes: 0
Views: 80
Reputation: 159754
date1.compareTo(date2)
From point #1:
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date date1 = sdf.parse(o1.getDatePublished());
Date date2 = sdf.parse(o2.getDatePublished());
return date1.compareTo(date2);
Upvotes: 1
Reputation: 256
Looks like the good method to compare dates. For the compilation error, rethrow an exception in your catch block or return an int value.
Upvotes: 1