public static void main(String[] args) {
List<String> dates = Arrays.asList("2020-01-19", "2020-02-19", "2019-01-18", "2019-02-11", "2019-01-19");
Collections.sort(dates, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
//字符串分割可使用正则表达式,需要加[],支持2020-01-19和2020/01/19两种日期格式
String[] split1 = o1.split("[-|/]");
String[] split2 = o2.split("[-|/]");
for (int i = 0; i < split1.length; i++) {
if (Integer.parseInt(split1[i])!=Integer.parseInt(split2[i])){
return Integer.parseInt(split1[i])-Integer.parseInt(split2[i]);
}
}
return 0;
}
});
//[2019-01-18, 2019-01-19, 2019-02-11, 2020-01-19, 2020-02-19]
System.out.println(dates);
}
字符串日期排序
最新推荐文章于 2023-11-29 14:45:13 发布