DateComparator (Format dateFormat) { // the idea is to build a date instance, change then each field // (milliseconds / seconds / etc) and check the change on the // parsed instance. If changing, for example, the seconds, does // not produce a different formatted string, the comparator will // not pay attention to the seconds, and so on Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(new Date().getTime()); if (change(calendar, dateFormat, Calendar.MILLISECOND)) { // Milliseconds affect the output, full comparison return new DateComparator() { @Override public long diff(Date o1, Date o2) { return o1.compareTo(o2); } }; } int divisor = 0; if (change(calendar, dateFormat, Calendar.SECOND)) { divisor = 1000; } else if (change(calendar, dateFormat, Calendar.MINUTE)) { divisor = 1000 * 60; } else if (change(calendar, dateFormat, Calendar.HOUR)) { divisor = 1000 * 60 * 60; } else if (change(calendar, dateFormat, Calendar.DAY_OF_YEAR)) { return new DayMonthYearComparator(calendar); } else if (change(calendar, dateFormat, Calendar.MONTH)) { return new MonthYearComparator(calendar); } else if (change(calendar, dateFormat, Calendar.YEAR)) { return new YearComparator(calendar); } else { // nothing affects the output, great formatter! return new DateComparator() { @Override public long diff(Date o1, Date o2) { return 0; } }; } return new TimeComparator(divisor); }