如何对Java中字符串格式的日期进行排序?

2022-09-01 02:15:48

我有一个字符串值,如arraylist

ArrayList<String> datestring=new ArrayList<String>();
datestring.add("01/21/2013 @03:13 PM");
datestring.add("01/21/2013 @04:37 PM");
datestring.add("01/21/2013 @10:41 AM");
datestring.add("01/21/2013 @10:48 AM");
datestring.add("01/22/2013 @06:16 AM");
datestring.add("01/22/2013 @06:19 AM");
datestring.add("01/21/2013 @05:19 PM");
datestring.add("01/21/2013 @05:19 PM");

任何机构可以帮助我对上面的列表进行排序吗?以便根据 AM 和 PM 格式对值进行排序。
排序后的预期输出应为

for (String s : datestring)
{
    System.out.println(s);
}

.

01/21/2013 @10:41 AM;
01/21/2013 @10:48 AM;
01/21/2013 @03:13 PM;
01/21/2013 @04:37 PM;
01/21/2013 @05:16 PM;
01/21/2013 @05:19 PM;
01/22/2013 @06:16 AM;
01/22/2013 @06:19 AM;

答案 1

试试这个

    Collections.sort(datestring, new Comparator<String>() {
        DateFormat f = new SimpleDateFormat("MM/dd/yyyy '@'hh:mm a");
        @Override
        public int compare(String o1, String o2) {
            try {
                return f.parse(o1).compareTo(f.parse(o2));
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
        }
    });

或使用 Java 8

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy '@'hh:mm a");
    Collections.sort(datestring, (s1, s2) -> LocalDateTime.parse(s1, formatter).
            compareTo(LocalDateTime.parse(s2, formatter)));

答案 2

可以使用下面给出的 compareTo 以字符串格式比较日期列表。

ArrayList<String> datestring=new ArrayList<String>();
datestring.add("01/21/2013 @03:13 PM");
datestring.add("01/21/2013 @04:37 PM");
datestring.add("01/21/2013 @10:41 AM");
datestring.add("01/21/2013 @10:48 AM");
datestring.add("01/22/2013 @06:16 AM");
datestring.add("01/22/2013 @06:19 AM");
datestring.add("01/21/2013 @05:19 PM");
datestring.add("01/21/2013 @05:19 PM");

Collections.sort(datestring, new Comparator<String>() {
                @Override
                public int compare(String object1, String object2) {
                    return object1.compareTo(object2);
                }
            });

通过使用此功能,您甚至不必将字符串解析为日期