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
Asked
Active
Viewed 127 times
1

thesupremo43
- 19
- 2
-
1Does this answer your question? [How to sort Date which is in string format in java?](https://stackoverflow.com/questions/14451976/how-to-sort-date-which-is-in-string-format-in-java) – Lal Jan 26 '22 at 19:00
-
You haven't really defined an order. How are times without dates compared to those with dates? Should we infer today's date? Do they always sort before items that include a date? E.g., if today is 26 Jan. 2022 and you have "06:00 AM" and "Jan 26 2022 12:00 PM", how would you sort them? – erickson Jan 26 '22 at 19:45
-
1you probably want to create a `LocalDateTime` for each value (using a `DateTimeFormatter`), store it in a list (`ArrayList`) and sort that list as required (`sort()` of `List` or `Collections.sort()`). – user16320675 Jan 26 '22 at 19:57
2 Answers
0
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.

WJS
- 36,363
- 4
- 24
- 39
-1
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)