How to order hours

5

I have the following method to sort a% String of Hours String:

 public static void ordenaHoras() {

        ArrayList<String> horasList = new ArrayList<String>();
        horasList.add("23:45");
        horasList.add("11:13");
        horasList.add("15:33");
        horasList.add("12:27");
        horasList.add("15:24");

        Collections.sort(horasList, new Comparator<String>() {

            private SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");

            @Override
            public int compare(String o1, String o2) {
                int result = -1;

                try {
                    result = sdf.parse(o1).compareTo(sdf.parse(o2));
                } catch (ParseException ex) {
                    ex.printStackTrace();
                }

                return result;
            }
        });

        for (String hora: horasList) {
            System.out.println(hora);
        }
    }

My problem is that the values of hours that start at number 12 are always wrong in the first place !!! The output of the above method execution is:

12:27
11:13
15:24
15:33
23:45
    
asked by anonymous 09.06.2016 / 23:01

1 answer

8

If the times are always in the 24h format and as strings, you do not need to convert them to compare ( that is, using SimpleDateFormat.parse ). Just compare to string. There it will be all in the desired order without difficulty. :)

Now, the problem is that for you 12:27 it's half a day and twenty-seven, but the system is considering midnight and twenty-seven because you used hh (lowercase). Try using HH (uppercase) in formatting. According to documentation :

  

H: Hour in day (0-23)

     

h: Hour in am / pm (1-12)

    
09.06.2016 / 23:09