Folks, I have a weird requirement. I have an Object which consists of a Date reference better known as endDate. Along with this there is another String field called as the status which picks values like 'Soon', 'Ended' and 'Closed' Such objects are in an ArrayList.
I want to implement a sorting Strategy on this.
First sorting to apply is based on Elapsed time. I want to First sort on EndDate, the difference of which is closest to now should be ranked 1st. i.e if the current Time is Sep 3,2015 7:34 PM IST and there exists an object with endDate as Sep 3,2015 7:36 PM IST.
Second is on the status the logic being all object with soon should appear first, then the ended ones and then closed.
Example : if the Input is
[0]( Sep 1,2015 10:36 PM IST ,ended)
[1]( Sep 3,2015 7:36 PM IST , soon )
[2]( Aug 29,2015 11:16 AM IST , closed)
[3]( Sep 7,2015 12:00 PM IST , soon )
[4]( Sep 1,2015 12:12 PM IST , ended)
Then the output should be
[0]( Sep 3,2015 7:36 PM IST , soon)
[1]( Sep 7,2015 12:00 PM IST , soon)
[2]( Sep 1,2015 10:36 PM IST ,ended)
[3]( Sep 1,2015 12:12 PM IST , ended)
[4]( Aug 29,2015 11:16 AM IST , closed)
Note : Timestamps used here are for representational purpose only
CODE : The compare implementation inside the comparator, The timestamps are read as GMT.
@Override
public int compare(JSONObject a, JSONObject b) {
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date currentdate = dateFormatLocal.parse( dateFormatGmt.format(new Date()));
} catch (ParseException e1) {
e1.printStackTrace();
}
try {
Date betEnds1 = dateFormatLocal.parse((String) a.get(KEY_NAME));
Date betEnds2 = dateFormatLocal.parse((String) b.get(KEY_NAME));
return betEnds1.compareTo(betEnds2);
}
catch (JSONException e) {
return -1;
} catch (ParseException e) {
return -1;
}
}