K Roy
K Roy

Reputation: 33

How to sort timestamp list?

I have a list of timestamp(long) in which I have to sort list base on time or list added.

I have tried and searched but its now working.

 Collections.sort(vehicles, new Comparator<VehicleListModel.Vehicle>() {
                @Override
                public int compare(VehicleListModel.Vehicle o1, VehicleListModel.Vehicle o2) {
                    try {
                        DateFormat format = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
                        return format.parse(o1.getCreated()).compareTo(format.parse(o2.getCreated()));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return 0;
                    }
                }
            });
            customerListAdapter.notifyDataSetChanged();

its not working then I tried this but this Date(timeStamp) is deprecated

please help

Upvotes: 1

Views: 27638

Answers (2)

Darshan Mehta
Darshan Mehta

Reputation: 30809

If getCreated returns a Date then you can compare two dates using compareTo and sort the list based on this comparison, e.g.:

List<VehicleListModel.Vehicle> list = new ArrayList<>();
list.sort((e1, e2) -> e1.getCreated().compareTo(e2.getCreated()));

update

If getCreated returns long value then you can box it and use compareTo method of Long class, e.g.:

List<ChainCode> list = new ArrayList<ChainCode>();
list.sort((e1, e2) -> new Long(e1.getCreated()).compareTo(new Long(e2.getCreated())));

Upvotes: 6

Jd Prajapati
Jd Prajapati

Reputation: 1971

Use long timestamp value for soring

     Collections.sort(vehicles, new Comparator<VehicleListModel.Vehicle>() {
                    @Override
                    public int compare(VehicleListModel.Vehicle o1, VehicleListModel.Vehicle o2) {
                        try {
                            DateFormat format = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
return Long.valueOf(format.parse(o1.getCreated()).getTime()).compareTo(format.parse(o2.getCreated()).getTime());

                        } catch (Exception e) {
                            e.printStackTrace();
                            return 0;
                        }
                    }
                });
                customerListAdapter.notifyDataSetChanged();

Upvotes: 1

Related Questions