如何在Java中的arraylist中获取带时间的升序日期

时间:2018-08-23 12:06:03

标签: java arrays sorting datetime

我有一个日期列表,例如:

  

20-aug-2018 05:34 pm,20-aug-2018 06:23 pm,20-aug-2018 04:03 pm,   2018年8月20日07:20 pm

现在,我想得到这样的输出:

  

20-aug-2018 04:03 pm,20-aug-2018 05:34 pm,20-aug-2018 06:23 pm,   2018年8月20日07:20 pm

3 个答案:

答案 0 :(得分:1)

如果输入为List<String>,则可以通过以下方式实现:

  1. 将日期字符串解析为LocalDateTime

  2. LocalDateTime具有可比性,只需致电list.sort

示例代码:

// initiate input
List<String> list = new ArrayList<>(Arrays.asList("20-aug-2018 05:34 pm", "20-Aug-2018 06:23 pm", "20-aug-2018 04:03 pm", "20-aug-2018 07:20 pm"));

// build a formatter which is used to parse the string to LocalDateTime
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern("dd-MMM-yyyy hh:mm a")
        .toFormatter(Locale.US);

// sort based on LocalDateTime
list.sort(Comparator.comparing(dateString -> LocalDateTime.parse(dateString, formatter)));
System.out.println(list);

输出:

[20-aug-2018 04:03 pm, 20-aug-2018 05:34 pm, 20-Aug-2018 06:23 pm, 20-aug-2018 07:20 pm]

答案 1 :(得分:0)

尝试一下:

Collections.sort(yourList)

答案 2 :(得分:0)

如果包含日期的列表的类型为java.util.Date,则 Collections.sort(yourList)应该适合您

如果列表的类型为String,则可以定义自己的comparator并在其中包含排序逻辑,然后将其传递给Collections.sort(yourList, yourcomparator)

public class SortDate {
public static void main(String[] args) {
    List<String> l = new ArrayList<>(Arrays.asList("20-aug-2018 04:03 pm", "22-aug-2018 07:20 pm",
            "25-aug-2018 06:23 pm", "19-aug-2018 07:20 pm", "08-aug-2018 05:34 pm"));
    Collections.sort(l, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm aa");
            Date d1 = null;
            Date d2 = null;
            try {
                // Parse the string using simpledateformat. The pattern I have taken based on your code
                d1 = sdf.parse(o1);
                d2 = sdf.parse(o2);
                return d1.compareTo(d2);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            // It this return then we have some issue with the string date given
            return -1;
        }

    });
    System.out.println(l);
}

}