问题
I am trying to sort the objects by Date and Time -> for example if the dates and times are: 24/04/2015 14:00 & 24/04/2015 09:00 & 25/04/2015 15:00 order should be this:
- 24/04/2015 09:00
- 24/04/2015 14:00
- 25/04/2015 15:00
In my case the order is this:
- 24/04/2015 14:00
- 24/04/2015 09:00
- 25/04/2015 15:00
It gets sorted by date, but ignores the time.
The code
Collections.sort(myObjects, new Comparator<MyObject>(){
@Override
public int compare(MyObject object1, MyObject object2) {
return object1.getDate().compareTo(object2.getDate());
}
});
P.S. getDate() method of myObject class is a regular getter which simply returns a java.util.Date object.
Am I missing something?
UPDATE
The Date was coming from MySQL DB, datatype is DATE, therefore it was loosing the exact time and the TIME was ignored during sorting. That is also a reason why I was not able to reproduce the problem, as I was always setting the Date objects manually considering the time.
回答1:
I tried following code and its sorting correctly. May be you can compare and find out if you have any issues the way you are populating the date object
public class DateSorter {
public static void main(String[] args) {
List<MyObject> myObjects = new ArrayList<MyObject>();
Calendar cal = new GregorianCalendar();
cal.set(2015, 4, 24, 14, 00);
Date dt1 = cal.getTime();
cal = new GregorianCalendar();
cal.set(2015, 4, 24, 9, 00);
Date dt2 = cal.getTime();
cal = new GregorianCalendar();
cal.set(2015, 4, 25, 15, 00);
Date dt3 = cal.getTime();
myObjects.add(new MyObject("1", dt1));
myObjects.add(new MyObject("2", dt2));
myObjects.add(new MyObject("3", dt3));
Collections.sort(myObjects, new Comparator<MyObject>() {
@Override
public int compare(MyObject object1, MyObject object2) {
return (int) (object1.getDate().compareTo(object2.getDate()));
}
});
System.out.println(myObjects.get(0));
System.out.println(myObjects.get(1));
System.out.println(myObjects.get(2));
}
}
回答2:
Try to compare by milliseconds value of date. (getTime() method).
来源:https://stackoverflow.com/questions/29364921/sorting-by-date-and-time-using-comparator