How to order hours

Asked

Viewed 311 times

5

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

 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 starting at number 12 always get wrongly first!!! The output of the execution of the top method is:

12:27
11:13
15:24
15:33
23:45

1 answer

8


If the hours are always on 24-hour format and as strings, you don’t need to convert them to compare (i.e., use the SimpleDateFormat.parse). Just compare in string even. Ai will get everything in the desired order without difficulty. :)

Now, the problem is that for you 12:27 is noon and twenty-seven, but the system is considering it as midnight and twenty-seven because you used hh (lower case). Experiment using HH (capital) in the format. According to documentation:

H: Hour in day (0-23)

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.