'How to sort Datetime using Java [closed]

I have a column with data some thing like below , if its current date then only time will be displayed otherwise entire date will be displayed. How to sort this using Java?
12:00 PM
10:01 AM
Jan 01 2022 09:03 AM
Dec 31 2021 05:51 PM
Dec 30 2021 03:47 PM
Dec 29 2021 12:05 PM



Solution 1:[1]

Here is one way.

String vals[] = { "12:00 PM",
        "10:01 AM", "Jan 01 2022 09:03 AM",
        "Dec 31 2021 05:51 PM", "Dec 30 2021 03:47 PM",
        "Dec 29 2021 12:05 PM" };
  • create a comparator and selectively parse the date. I am simply using if first char of string is a digit or not. There may be better ways.
  • then create LocalDateTime instance on which to sort.
  • then pass the array and comparator to Arrays.sort
DateTimeFormatter dateTime =DateTimeFormatter
                 .ofPattern("MMM dd yyyy h:mm a");
DateTimeFormatter time =DateTimeFormatter.ofPattern("h:mm a");
  • check first digit.
  • either create current date with added time
  • or parse the supplied String as a a date and time
Comparator<String> comp = Comparator.comparing(
        str->Character.isDigit(str.charAt(0)) ?                  
           LocalDate.now().atTime(LocalTime.parse(str,time)) : 
           LocalDateTime.parse(str,dateTime),
                Comparator.naturalOrder());

Arrays.sort(vals, comp);        

for (String str : vals) {
    System.out.println(str);
}

prints

Dec 29 2021 12:05 PM
Dec 30 2021 03:47 PM
Dec 31 2021 05:51 PM
Jan 01 2022 09:03 AM
10:01 AM
12:00 PM

If you want the sorting in reverse order then change Comparator.naturalOrder() to Comparator.reverseOrder() in the defined Comparator above.

Solution 2:[2]

You can split each line by spaces, and store the results on a collection, and the size of the collection will tell you if it's the current date, or not, and walking through your collection from the end you can store information in date type objects, and then store these objects a list of dates, and then you can compare them based on the compareTo method of java.util.Date.

date1.compareTo(date2)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 MEHDI BENREFAD