Sorting by DATE and TIME using Comparator

筅森魡賤 提交于 2021-02-05 09:45:34

问题


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:

  1. 24/04/2015 09:00
  2. 24/04/2015 14:00
  3. 25/04/2015 15:00

In my case the order is this:

  1. 24/04/2015 14:00
  2. 24/04/2015 09:00
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!