-1

I looking for a solution to parse the String date.

 datestring.add("2019-02-17T18:39:02");
 datestring.add("2019-02-17T18:39:01");
 datestring.add("2019-02-17T18:39:03");
 datestring.add("2019-02-17T18:39:07");

datastring is the ArrayList of String date.

  Collections.sort(datestring, new Comparator<String>() {
        DateFormat f = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss a");

        @Override
        public int compare(String o1, String o2) {
            try {
                return f.parse(o1).compareTo(f.parse(o2));
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
        }
    });

So here i am trying to sort the list based on date. But I am getting ParseException:-

Caused by: java.lang.IllegalArgumentException: java.text.ParseException: Unparseable date: "2019-02-17T18:39:07"
jibs
  • 3
  • 1
  • 5
  • These are the values actually I am getting from backend service. Help would be appreciated. – jibs Apr 09 '19 at 05:34
  • 1
    your incoming date is in format `yyyy-MM-dd'T'hh:mm:ss` try using this format to parse your date – karan Apr 09 '19 at 05:36
  • Have look [this](https://stackoverflow.com/a/35389674/5110595) – Hemant Parmar Apr 09 '19 at 05:41
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Apr 10 '19 at 05:51

2 Answers2

2

Your incoming date is in format yyyy-MM-dd'T'hh:mm:ss and the format you are using is dd-MMM-yyyy HH:mm:ss a which will not generate error.

Try parsing your incoming date string using yyyy-MM-dd'T'hh:mm:ss and then convert it to some other format if you want.

karan
  • 8,637
  • 3
  • 41
  • 78
1

java.time

    List<String> datestring = new ArrayList<String>();

    datestring.add("2019-02-17T18:39:02");
    datestring.add("2019-02-17T18:39:01");
    datestring.add("2019-02-17T18:39:03");
    datestring.add("2019-02-17T18:39:07");

    Collections.sort(datestring, Comparator.comparing(LocalDateTime::parse));
    System.out.println(datestring);

Output from this snippet is:

[2019-02-17T18:39:01, 2019-02-17T18:39:02, 2019-02-17T18:39:03, 2019-02-17T18:39:07]

Your strings are in ISO 8601 format, the international standard for date and time format. LocalDateTime and the other classes of java.time, the modern Java date and time API, parse (and print) ISO 8601 format as their default, that is, without any explicit formatter.

Comparator.comparing was introduced in Java 8 and accepts a lambda or as (as here) a method reference. If you can use it on your API level, the advantage is not only that it’s brief, but even more that it is hard to get wrong.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161