首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java的arraylist中获得随时间上升的日期

如何在java的arraylist中获得随时间上升的日期
EN

Stack Overflow用户
提问于 2018-08-23 12:06:03
回答 3查看 69关注 0票数 0

我有一份日期清单,如:

2018年8月20日至2018年0时34分、2018年8月20日至2018年06时23分、2018年8月20日至2018年04日下午03时、2018年8月20日至2018年07月20时20分

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

2018年8月20日至2018年0时03分,2018年8月20日至2018年5时34分,2018年8月20日至2018年06时23分,2018年8月20日至2018年07月20时20分

EN

回答 3

Stack Overflow用户

发布于 2018-08-23 12:40:45

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

  1. 将日期字符串解析为LocalDateTime
  2. LocalDateTime是可比的,只需调用list.sort

样本代码:

代码语言:javascript
复制
// 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);

产出:

代码语言:javascript
复制
[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
EN

Stack Overflow用户

发布于 2018-08-23 12:10:24

试试这个:

代码语言:javascript
复制
Collections.sort(yourList)
票数 0
EN

Stack Overflow用户

发布于 2018-08-23 12:21:52

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

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

代码语言:javascript
复制
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);
}

}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51985454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档