简体   繁体   English

如何在Java中按日期/时间比较和排序列表?

[英]How to compare and order list by date/time in java?

How do i implement a java comparator class which can sort the order of the list of date/time strings? 我如何实现一个Java比较器类,该类可以对日期/时间字符串列表的顺序进行排序?

Like eg 像例如

i have 我有

2012-06-15T12:01:00.000+08:00
2012-06-25T12:15:00.000+08:00
2012-06-08T00:00:00.000Z

Then it should be sorted like 然后应该像

2012-06-08T00:00:00.000Z
2012-06-15T12:01:00.000+08:00
2012-06-25T12:15:00.000+08:00

You have two issues here (since parsing the strings directly is not going to work). 这里有两个问题(因为直接解析字符串不起作用)。

  1. Convert your strings into dates. 将您的字符串转换为日期。 See SimpleDateFormat for more info and the DateFormat.parse() method 有关更多信息,请参见SimpleDateFormatDateFormat.parse()方法。
  2. Sort the subsequent dates in a collection using Collections.sort . 使用Collections.sort对集合中的后续日期进行排序。

Parse them into java.util.Date . 将它们解析为java.util.Date Date already implements Comparable 日期已实施Comparable

well, If you want a quick solution, it is as follows. 好吧,如果您想快速解决问题,请按照以下步骤进行操作。

http://www.ltg.ed.ac.uk/NITE/nxt/apidoc/net/sourceforge/nite/util/SortedList.html . http://www.ltg.ed.ac.uk/NITE/nxt/apidoc/net/sourceforge/nite/util/SortedList.html

Also, if you are confidant every date will be different, then do use TreeSet.You can use them as follows. 另外,如果您对自己的密信感到满意,那么每个日期都会有所不同,那么请使用TreeSet。您可以按以下方式使用它们。

Make a new TreeSet and keep adding your dates in them. 创建一个新的TreeSet并继续在其中添加日期。 It will be automatically sorted, As TreeSet sorts all objects it contains, if they implement comparable.(or comparator provided). 如果TreeSet实现了可比较的对象(或提供的比较器),则它将自动排序,因为TreeSet对其包含的所有对象进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM