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
How to sort timestamp list?
提问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 getCreated
returns a Date
then you can compare two dates using compareTo
and 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 getCreated
returns long
value then you can box it and use compareTo
method of Long
class, 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();