[英]How to sort Date which is in string format in java?
I have an arraylist
with string values like我有一个带有字符串值的
arraylist
列表,例如
ArrayList<String> datestring=new ArrayList<String>();
datestring.add("01/21/2013 @03:13 PM");
datestring.add("01/21/2013 @04:37 PM");
datestring.add("01/21/2013 @10:41 AM");
datestring.add("01/21/2013 @10:48 AM");
datestring.add("01/22/2013 @06:16 AM");
datestring.add("01/22/2013 @06:19 AM");
datestring.add("01/21/2013 @05:19 PM");
datestring.add("01/21/2013 @05:19 PM");
Can any body help me on sorting the above list?任何机构都可以帮助我对上述列表进行排序吗? So that the values are sorted according to AM and PM format.
以便根据 AM 和 PM 格式对值进行排序。
The expected output after sorting should be排序后的预期输出应该是
for (String s : datestring)
{
System.out.println(s);
}
. .
01/21/2013 @10:41 AM;
01/21/2013 @10:48 AM;
01/21/2013 @03:13 PM;
01/21/2013 @04:37 PM;
01/21/2013 @05:16 PM;
01/21/2013 @05:19 PM;
01/22/2013 @06:16 AM;
01/22/2013 @06:19 AM;
try this尝试这个
Collections.sort(datestring, new Comparator<String>() {
DateFormat f = new SimpleDateFormat("MM/dd/yyyy '@'hh:mm a");
@Override
public int compare(String o1, String o2) {
try {
return f.parse(o1).compareTo(f.parse(o2));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
});
or with Java 8或使用 Java 8
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy '@'hh:mm a");
Collections.sort(datestring, (s1, s2) -> LocalDateTime.parse(s1, formatter).
compareTo(LocalDateTime.parse(s2, formatter)));
One can compare the List of date in string format by using the compareTo as given below.可以使用下面给出的 compareTo 以字符串格式比较日期列表。
ArrayList<String> datestring=new ArrayList<String>();
datestring.add("01/21/2013 @03:13 PM");
datestring.add("01/21/2013 @04:37 PM");
datestring.add("01/21/2013 @10:41 AM");
datestring.add("01/21/2013 @10:48 AM");
datestring.add("01/22/2013 @06:16 AM");
datestring.add("01/22/2013 @06:19 AM");
datestring.add("01/21/2013 @05:19 PM");
datestring.add("01/21/2013 @05:19 PM");
Collections.sort(datestring, new Comparator<String>() {
@Override
public int compare(String object1, String object2) {
return object1.compareTo(object2);
}
});
By using this you even dont have to parse the String into date通过使用它,您甚至不必将字符串解析为日期
One option is to add the dates to a TreeMap, with the unformatted date as the key, and the formatted date as the value.一种选择是将日期添加到 TreeMap,将未格式化的日期作为键,将格式化的日期作为值。 Using a TreeMap will sort the values automatically.
使用 TreeMap 将自动对值进行排序。
private ArrayList<String> sortDates(ArrayList<String> dates) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("dd MMM yyyy");
Map <Date, String> dateFormatMap = new TreeMap<>();
for (String date: dates)
dateFormatMap.put(f.parse(date), date);
return new ArrayList<>(dateFormatMap.values());
}
First, as bowmore has already said , you should not keep strings in your list.首先,正如鲍莫尔已经说过的那样,您不应该在列表中保留字符串。 Instead, use instances of java.time classes.
相反,使用java.time类的实例。
Keep LocalDateTime
objects.保留
LocalDateTime
对象。 Or ZonedDateTime
if you know in which time zone the times are.或者
ZonedDateTime
如果您知道时间在哪个时区。 Strings are good for presentation to the user, not for manipulation in your program such as sorting.字符串有利于向用户展示,而不是用于在您的程序中进行操作,例如排序。
The following code converts your list to a List<LocalDateTime>
:以下代码将您的列表转换为
List<LocalDateTime>
:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MM/dd/uuuu '@'hh:mm a", Locale.ENGLISH);
List<LocalDateTime> dateTimeList = datestring.stream()
.map(ds -> LocalDateTime.parse(ds, formatter))
.collect(Collectors.toCollection(ArrayList::new));
Now sorting is straightforward:现在排序很简单:
dateTimeList.sort(Comparator.naturalOrder());
LocalDateTime
have a natural order since they implement Comparable
, so Comparator.naturalOrder()
is fine for sorting. LocalDateTime
具有自然顺序,因为它们实现了Comparable
,因此Comparator.naturalOrder()
适合排序。 Another way of obtaining the same sorting is:获得相同排序的另一种方法是:
dateTimeList.sort(LocalDateTime::compareTo);
To present the sorted data to the user we want to format the date-times into strings, of course:为了将排序后的数据呈现给用户,我们当然希望将日期时间格式化为字符串:
dateTimeList.forEach(ldt -> System.out.println(ldt.format(formatter)));
The output is:输出是:
01/21/2013 @10:41 AM
01/21/2013 @10:48 AM
01/21/2013 @03:13 PM
01/21/2013 @04:37 PM
01/21/2013 @05:19 PM
01/21/2013 @05:19 PM
01/22/2013 @06:16 AM
01/22/2013 @06:19 AM
Except for the semicolons and a single simple typo I believe this is precisely what you asked for.除了分号和一个简单的错字,我相信这正是您所要求的。
Link: Oracle tutorial: Date Time explaining how to use java.time
, the modern Java date and time API that includes LocalDateTime
and DateTimeFormatter
.链接: Oracle 教程:Date Time解释如何使用
java.time
,现代 Java 日期和时间 API,包括LocalDateTime
和DateTimeFormatter
。
While there is a technical way to get around your problem, the basic mistake is to represent Date
s as String
s, a form of 'primitive obsession'.虽然有一种技术方法可以解决您的问题,但基本错误是将
Date
s 表示为String
s,这是“原始痴迷”的一种形式。 If you have textual input, convert it to java.util.Date
or an appropriate joda class ( LocalDateTime
seems appropriate here).如果您有文本输入,请将其转换为
java.util.Date
或适当的 joda 类( LocalDateTime
在这里似乎合适)。 These classes implement Comparable
out of the box, and sorting them is easy.这些类开箱即用地实现了
Comparable
,并且对它们进行排序很容易。 But they also have all the other logic on board you're likely to need when manipulting date/time instances, Strings do not.但是它们还具有您在处理日期/时间实例时可能需要的所有其他逻辑,而字符串则没有。
Update更新
Since java 8 I'd hihgly recommend using its LocalDateTime class instead.从 java 8 开始,我强烈推荐使用它的LocalDateTime类。
ArrayList doesnt support sorting by default. ArrayList 默认不支持排序。 You can use
您可以使用
public static <T> void sort(List<T> list, Comparator<? super T> c)
from java.util.Collections
class. public static <T> void sort(List<T> list, Comparator<? super T> c)
来自java.util.Collections
类。 pass your implementation of comparator to sort dates, something like将比较器的实现传递给对日期进行排序,例如
http://www.coderanch.com/t/392338/java/java/compare-Dates-String-Format http://www.coderanch.com/t/392338/java/java/compare-Dates-String-Format
In Your class add this.在您的班级中添加此内容。
protected LocalDateTime getTrnDateLocalFormat() {
LocalDateTime localDateTime = LocalDateTime.parse(this.yourDate.toLowerCase(), DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm:ss a"));
return localDateTime;
}
.sorted(Comparator.comparing(YourClass::getTrnDateLocalFormat)).collect(Collectors.toList());
Probably you can write a custom comparator to compare the Date Strings and order based on the requirement.可能您可以编写一个自定义比较器来根据要求比较日期字符串和顺序。 Then you would be able to sort the collection with the implemented comparator.
然后,您将能够使用实现的比较器对集合进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.