0

I am using the following code to parse date to sort a list:

Collections.sort(collaborationRoomModelList, new Comparator<CollaborationRoomModel>() {
                    DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");

                    @Override
                    public int compare(CollaborationRoomModel lhs, CollaborationRoomModel rhs) {
                        try {
                            return f.parse(rhs.getDate()).compareTo(f.parse(lhs.getDate()));
                        } catch (ParseException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                });

This code works perfectly fine on Android 7 but crashes in android 12. Below is the crash log:

java.lang.IllegalArgumentException: java.text.ParseException: Unparseable date: "Tue Jun 07 14:40:24 GMT+10:00 2022"
        at com.bizfluence.ui.business.collabmsglist.CollabMessageList$3$1.compare(CollabMessageList.java:389)
        at com.bizfluence.ui.business.collabmsglist.CollabMessageList$3$1.compare(CollabMessageList.java:381)
        at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
        at java.util.TimSort.sort(TimSort.java:220)
        at java.util.Arrays.sort(Arrays.java:1492)
        at java.util.ArrayList.sort(ArrayList.java:1470)
        at java.util.Collections.sort(Collections.java:206)
       

Any solution to fix this issue is greatly appreciated.

TharakaNirmana
  • 10,237
  • 8
  • 50
  • 69
  • 1
    How does the same date get formatted in Android 7? I'm guessing it's formatting the timezone differently. You can also optionally specify a Locale in the `SimpleDateFormat` constructor, so try that. – Gavin Wright Jun 10 '22 at 06:13
  • @GavinWright thank you for your input, I added Locale and works fine now on both Android 7 and 12. – TharakaNirmana Jun 10 '22 at 06:50
  • Consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. Use [desugaring](https://developer.android.com/studio/write/java8-support-table) in order to use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It is so much nicer to work with. – Ole V.V. Jun 10 '22 at 15:04

1 Answers1

0

Adding the Local solved the issue. Works fine on both android 7 and 12.

DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.US);
TharakaNirmana
  • 10,237
  • 8
  • 50
  • 69