6

I am in a need of function, user defined, which could sort the dates from current time to old time.

I'm having list of 10 dates which I want to sort these dates starting from last recent date.

Currently I have a logic, in which if we can covert the date in milli-second then comparing it with current-milli-seconds and the least milli-second will be the recent date. That is,

CURRENT_MILLI_SECOND - A_DATE_CONVERTED_TO_MILLI_SECONDS = MILLI-SECONDS

Please suggest me if anyone can help me in this logic or any other logics...!!!

This is the formate which I am getting from server:

Thu Dec 27 11:02:43 GMT+05:30 2012
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
Sam-In-TechValens
  • 2,501
  • 4
  • 34
  • 67

7 Answers7

7

You can go with Comparator and can sort data by using compare()

Collections.sort(dateList, new Comparator<Date>(){
           public int compare(Date date1, Date date2){
          return date1.after(date2);
        }
      });
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
  • So if I have 10 dates in a list, then how can I use this method to get which is the most recent date......!!! – Sam-In-TechValens Dec 27 '12 at 05:58
  • Thanks alot, Can I use this in Android too?? – Sam-In-TechValens Dec 27 '12 at 06:03
  • 1
    You can use `Collections` class and sort your List with *Comparator*, Yes you can use the same in Android too. – Mohammed Azharuddin Shaikh Dec 27 '12 at 06:03
  • If you have date in milliseconds, put that in string, and pass the same values to compare method. You will get your dates sorted according to milliseconds that way. – DroidDev Aug 08 '14 at 07:13
  • FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. Much of the java.time functionality is back-ported to Java 6 & Java 7 in the [ThreeTen-Backport](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Jan 14 '18 at 01:26
5

Try this:

 Comparator date_comparator = new Comparator() {
    @Override
    public int compare(Date date1, Date date2){
    return date1.compareTo(date2);
    }
    };
howettl
  • 12,419
  • 13
  • 56
  • 91
sunil jain
  • 104
  • 6
1

You can use Calendar or Date class to do so. Using calendar and Date you can compare two dates like date1.compare(date2) or date.before(date2) or date1.after(date2) such api's are available for your cases.

Daud Arfin
  • 2,499
  • 1
  • 18
  • 37
1

tl;dr

Collections.reverse(
    new ArrayList<>().add( 
        OffsetDateTime.parse( 
            "Thu Dec 27 11:02:43 GMT+05:30 2012" , 
            DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss OOOO uuuu" , Locale.US  ) 
        ) 
    )
)

java.time

The modern approach uses java.time classes.

Define a formatting pattern to match. By the way, this is a terrible format; if you have any control, use standard ISO 8601 formats instead.

String input = "Thu Dec 27 11:02:43 GMT+05:30 2012" ;

DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss OOOO uuuu" , Locale.US  );

Your input strings specify an offset-from-UTC but not a full time zone. So we parse as an OffsetDateTime.

OffsetDateTime odt = OffsetDateTime.parse( input , f );

odt.toString(): 2012-12-27T11:02:43+05:30

OffsetDateTime objects already know how to sort themselves, as they implement Comparable.

List< OffsetDateTime > odts = new ArrayList<>( 3 ) ;
odts.add( odt ) ;
odts.add( odt.plusMinutes( 7 ) ) ;
odts.add( odt.minusMinutes( 21 ) ) ;

Collections.sort( odts ) ;

You want the most recent at top of the list, so sort in reverse order.

Collections.reverse( odts ) ;  // Reverse-order.

To compare individual java.time objects, call the isBefore, isAfter, and isEqual/equals methods.

thisOdt.isBefore( thatOdt )

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

The Date and Calendar classes in Java already have a good API to compare dates.

You can use this to write your own function for sorting the dates.

You can refer this link.

TechSpellBound
  • 2,505
  • 6
  • 25
  • 36
  • here is an example using Calendar Collections.sort(drawings,new Comparator() { @Override public int compare(Object o, Object t1) { return ((Drawing)t1).getCalendar().compareTo(((Drawing)o).getCalendar()); } }); – Michael Kern Aug 11 '16 at 04:23
0

There is my gist which will help you. You've just needed to pass unsorted date strings and date pattern in the parameters of SortedDateGenerator.getSortedDates(List<String> unSortedDate,String datePattern) function then you will get the strings of the sorted date . If you need Date object instead then you can modify my code as your requirements.

Gk Mohammad Emon
  • 6,084
  • 3
  • 42
  • 42
0

Simply call getSortedDateList method to get the dates sorted as per your requirement

private ArrayList<Date> getSortedDateList(ArrayList<Date> dateList) {
        //Replace year with current year to sort in jan to dec order
        for(int i = 0; i < dateList.size(); i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateList.get(i));
            calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
            dateList.set(i, calendar.getTime());
        }
        //Sort all dates in ascending order
        Collections.sort(dateList);
        //Get final index of past dates
        int index = 0;
        for (int i = 0; i < dateList.size(); i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateList.get(i));
            calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
            Calendar today = Calendar.getInstance();
            today.set(Calendar.DATE, Calendar.getInstance().get(Calendar.DATE) - 1);
            if (calendar.getTime().after(today.getTime())) {
                index = i;
                break;
            }
        }
        //New list for storing upcoming dates
        ArrayList<Date> newList = new ArrayList<>();
        
        //Store upcoming dates in new list
        for (int i = index; i < dateList.size(); i++) {
            newList.add(dateList.get(i));
        }
        //Store past dates in new list
        for (int i = 0; i < index; i++) {
            newList.add(dateList.get(i));
        }
        Collections.copy(dateList, newList);
        return dateList;
    }

For example, store some sample dates to array list and call getSortedDateList method

SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy"); // Your date format
        
ArrayList<Date> dateList = new ArrayList<>();
dateList.add(formatter.parse("Thu May 25 00:00:00 GMT+05:30 2000"));
dateList.add(formatter.parse("Tue Apr 18 00:00:00 GMT+05:30 2021"));
dateList.add(formatter.parse("Wed Jan 27 00:00:00 GMT+05:30 1997"));
dateList.add(formatter.parse("Sat Feb 22 00:00:00 GMT+05:30 2020"));
dateList.add(formatter.parse("Mon Dec 20 00:00:00 GMT+05:30 2001"));
dateList.add(formatter.parse("Thu Jun 14 00:00:00 GMT+05:30 2009"));
dateList.add(formatter.parse("Sat Mar 01 00:00:00 GMT+05:30 1999"));
dateList.add(formatter.parse("Sat Nov 07 00:00:00 GMT+05:30 2005"));
        
dateList = getSortedDateList(dateList);
        
for(Date date: dateList) {
    System.out.println(date.toString());
}

If current date is Feb 01 2021, then the final output will be as shown below

Mon Feb 22 00:00:00 IST 2021
Mon Mar 01 00:00:00 IST 2021
Sun Apr 18 00:00:00 IST 2021
Tue May 25 00:00:00 IST 2021
Mon Jun 14 00:00:00 IST 2021
Sun Nov 07 00:00:00 IST 2021
Mon Dec 20 00:00:00 IST 2021
Wed Jan 27 00:00:00 IST 2021
niranj1997
  • 719
  • 8
  • 16