我有一份日期清单,如:
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分
发布于 2018-08-23 12:40:45
如果输入为List<String>,则可以通过以下方式实现:
LocalDateTimeLocalDateTime是可比的,只需调用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]发布于 2018-08-23 12:10:24
试试这个:
Collections.sort(yourList)发布于 2018-08-23 12:21:52
如果包含日期的列表是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);
}}
https://stackoverflow.com/questions/51985454
复制相似问题