Sam-In-TechValens
Sam-In-TechValens

Reputation: 2519

How to sort the dates from current to old date in Android or Java?

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

Upvotes: 6

Views: 12734

Answers (7)

niranj1997
niranj1997

Reputation: 857

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

Upvotes: 0

Gk Mohammad Emon
Gk Mohammad Emon

Reputation: 6938

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.

Upvotes: 0

Basil Bourque
Basil Bourque

Reputation: 338684

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?

Upvotes: 1

sunil jain
sunil jain

Reputation: 102

Try this:

 Comparator date_comparator = new Comparator() {
    @Override
    public int compare(Date date1, Date date2){
    return date1.compareTo(date2);
    }
    };

Upvotes: 5

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);
        }
      });

Upvotes: 7

TechSpellBound
TechSpellBound

Reputation: 2555

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.

Upvotes: 0

Daud Arfin
Daud Arfin

Reputation: 2499

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.

Upvotes: 1

Related Questions