簡體   English   中英

在 Java 中將日期列表排序為字符串

[英]Sorting a list of dates as a String in Java

我的arrayList中有一個日期列表作為字符串。 我需要從此列表中獲取最低日期值,然后與“dd-MM-yy”格式的日期進行比較。 我怎樣才能做到這一點??

這是我的代碼::

List<String> dateList = new ArrayList<String>();
for(DailyDataReading ddr: finalResult){
    dateList.add(sdf.format(ddr.getDailyReadingDate()));
}

Collections.sort(dateList);

if((sdf.format("date which is to be compared")).compareTo(dateList.get(dateList.size()-1))<=0)
 {...}
List<String> dateList;// This is your list of dates in string format
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yy");// This is a formatter to convert from your pattern to a LocalDate
List<LocalDate> dates = dateList.stream().map(dateString -> LocalDate.parse(dateString, dateTimeFormatter)).collect(Collectors.toList());// Use Java 8 streams to map the dates strings to LocalDate objects
Collections.sort(dates);// Sort the list
LocalDate earliestDate = dates.get(0);// Take the lowest date value from the list
LocalDate specialDate = LocalDate.parse("some date", dateTimeFormatter);// create a date object for the date that you want to compare it to
earliestDate.compareTo(specialDate);// compare them

如果您的字符串都是dd-MM-yy形式的所有日期值,並且您想按時間順序對這些日期字符串進行排序,假設所有年份都來自本世紀(即 2000-2099 年),那么您就是這樣做的它。

Collections.sort(dateList, (d1,d2) -> {
    int cmp = d1.substring(6, 8).compareTo(d2.substring(6, 8));
    if (cmp == 0)
        cmp = d1.substring(3, 5).compareTo(d2.substring(3, 5));
    if (cmp == 0)
        cmp = d1.substring(0, 2).compareTo(d2.substring(0, 2));
    return cmp;
});

“此列表中的最低日期值”是第一個值,即dateList.get(0)

Collections.sort(list_of_dates, new CustomComparator());

 public class CustomComparator implements Comparator<MyObject> {// MyObject would be Model class Date date1,date2; @Override public int compare(MyObject obj1, MyObject obj2) { DateFormat df1 = new SimpleDateFormat("dd, MMM yyyy"); try { date1 = df1.parse(obj1.getDate()); date2 = df1.parse(obj2.getDate()); } catch (ParseException e) { e.printStackTrace(); } return date1.compareTo(date2); } }

Collections.reverse(list_of_dates);

這將首先按最新對您的列表進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM