0

I am getting multiple dates from UI which I store in list. I want to sort these dates

List<String> li = new ArrayList<>();
li.add("11/1/2022 2:59 am");
li.add("10/21/2022 9:33 pm"); li.add("10/20/2022 8:26 am");

and so on

I am trying to sort with following code

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a", Locale.US);

Collections.sort(li, (s1, s2) -> LocalDateTime.parse(s1, formatter).
        compareTo(LocalDateTime.parse(s2, formatter)));

but getting error

"Exception in thread "main" java.time.format.DateTimeParseException: Text '10/21/2022 9:33 pm' could not be parsed at index 11"

The accepted solution at How to sort Date which is in string format in java? is not working for me. Could anyone please help here?

nikhil udgirkar
  • 367
  • 1
  • 7
  • 23
  • 1
    `DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/d/yyyy h:mm a", Locale.UK);` does it for me ;) – g00se Nov 17 '22 at 18:02
  • Why are you adding strings to your list? That’s bad data modelling. You should make yourself a list of `LocalDateTime` objects (or `ZonedDateTme`) and defer formatting to the time when you display the result to the user. – Ole V.V. Nov 17 '22 at 18:04
  • @OleV.V. I get this from UI. I am doing UI test automation – nikhil udgirkar Nov 18 '22 at 05:45
  • I would still store proper datre-time objects. If you indispensably need the exact string you got from the UI, then objects holding both even though it’s redundant. – Ole V.V. Nov 18 '22 at 05:50
  • @OleV.V. you mean using List?. Since from the automation it is retrieved in String as it has textContent() method. I thought rather than typecasting it to LocalDateTime let's store it as it is in String. Anyway I have got it working. Can you please provide me reference code so that I can study – nikhil udgirkar Nov 18 '22 at 06:08
  • There’s an example of what I suggest [in my answer here](https://stackoverflow.com/a/52776978/5772882). – Ole V.V. Nov 18 '22 at 21:15

0 Answers0