java 如何对时间戳列表进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44238533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:01:30  来源:igfitidea点击:

How to sort timestamp list?

javaandroidsortingdatetimestamp

提问by K Roy

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 thisbut this Date(timeStamp)is deprecated

它不工作然后我尝试了 这个,但这Date(timeStamp)已被弃用

please help

请帮忙

回答by Darshan Mehta

If getCreatedreturns a Datethen you can compare two dates using compareToand sort the list based on this comparison, e.g.:

如果getCreated返回 aDate那么您可以使用比较两个日期compareTo并根据此比较对列表进行排序,例如:

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

update

更新

If getCreatedreturns longvalue then you can box it and use compareTomethod of Longclass, e.g.:

如果getCreated返回long值,那么您可以将其装箱并使用类的compareTo方法Long,例如:

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

回答by Jd Prajapati

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