The decision to set milliseconds to 0 has a problem: if the dates are 12: 14: 29.999 and 12: 14: 30.003, you will set the dates to 12:14:29 and 12:14:30, respectively, and will find a difference that you do not want.
I thought of a comparator:
private static class SecondsComparator implements Comparator<Calendar> { public int compare(Calendar o1, Calendar o2) { final long difference = o1.getTimeInMillis() - o2.getTimeInMillis(); if (difference > -1000 && difference < 1000) return 0; else return difference < 0 ? 1 : -1; } } public static void main(String args[]) { Calendar c1 = Calendar.getInstance(); Utils.waitMilliseconds(100); Calendar c2 = Calendar.getInstance();
However, this is not a good solution, as this comparator violates the following rule:
The developer must ensure that x.compareTo (y) == 0 means that sgn (x.compareTo (z)) == sgn (y.compareTo (z)) for all z.
Which leads to (x=y and y=z) => x=z .
So, I see no solution ... But really, if you define several different dates, they are different, right?
Olivier faucheux
source share