如何在 Java 中对字符串数组中的日期进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25677690/
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 dates in a string array in Java?
提问by udeshplus
I want to create a date array and sort it. This is how I was able to do it but this is not what I required.
我想创建一个日期数组并对其进行排序。这就是我能够做到的,但这不是我所需要的。
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy");
java.util.Date date1 = sdf.parse("05-03-2014");
java.util.Date date2 = sdf.parse("23-08-2014");
java.util.Date dates[] = {date1, date2};
java.util.Arrays.sort(dates);
System.out.println(java.util.Arrays.toString(dates));
Because I have a String array "String dates[] = {"05-11-2014", "23-08-2014","05-02-2013"};" So I have to sort the dates in the string array. How do I change my code?
因为我有一个字符串数组 "String date[] = {"05-11-2014", "23-08-2014","05-02-2013"};" 所以我必须对字符串数组中的日期进行排序。如何更改我的代码?
回答by MadProgrammer
The better way would be to convert the String
array to an array of Date
更好的方法是将String
数组转换为数组Date
Date[] arrayOfDates = new Date[dates.length];
for (int index = 0; index < dates.length; index++) {
arrayOfDates[index] = sdf.parse(dates[index]);
}
Then sort the arrayOfDates
and if you need to, use the SimpleDateFormat
to format the results back to the dates
array...
然后排序arrayOfDates
,如果需要,使用SimpleDateFormat
将结果格式化回dates
数组...
Arrays.sort(arrayOfDates);
for (int index = 0; index < dates.length; index++) {
dates[index] = sdf.format(arrayOfDates[index]);
}
This provides you with much more control over what you should do if one or more of the values in the dates
array is an invalid format.
如果dates
数组中的一个或多个值是无效格式,这使您可以更好地控制应该做什么。
Another, "dirty" solution, would be to use a custom Comparator
that would convert the values to a Date
inline and compare them.
另一个“肮脏”的解决方案是使用自定义Comparator
将值转换为Date
内联并比较它们。
This is okay if you can guarantee the validity of the dates
, but starts to fall apart when you can't, for example...
如果您可以保证 的有效性,这是可以的dates
,但是当您不能保证时就会开始崩溃,例如......
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DirtySort {
public static void main(String[] args) {
String dates[] = {"05-11-2014", "23-08-2014","05-02-2013"};
Arrays.sort(dates, new Comparator<String>() {
private SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy");
@Override
public int compare(String o1, String o2) {
int result = -1;
try {
result = sdf.parse(o1).compareTo(sdf.parse(o2));
} catch (ParseException ex) {
ex.printStackTrace();
}
return result;
}
});
for (String date : dates) {
System.out.println(date);
}
}
}
回答by Basil Bourque
Use Date-Time Type
使用日期时间类型
The answer by MadProgrammeris correct. When working with date-time values, work with them as date-time data types. That's generally best. If you had a bunch of strings representing numbers, wouldn't you convert to numeric data types for your business logic?
MadProgrammer的回答是正确的。使用日期时间值时,将它们用作日期时间数据类型。这通常是最好的。如果您有一堆表示数字的字符串,您是否会为您的业务逻辑转换为数字数据类型?
Avoid java.util.Date
避免 java.util.Date
My only improvement to the other answer is to advise against using java.util.Date. Both that class and .Calendar that are bundled with Java are notoriously troublesome and should be avoided.
我对另一个答案的唯一改进是建议不要使用 java.util.Date。与 Java 捆绑的那个类和 .Calendar 都是出了名的麻烦,应该避免。
Instead use the Joda-Timelibrary or the new java.time packagein Java 8 inspired by Joda-Time.
而是使用Joda-Time库或Java 8 中受 Joda-Time 启发的新java.time 包。
Date-Only
仅限日期
Both Joda-Time and java.time offer a LocalDate
class to handle a date-only value without any time-of-day or time zone. Just the thing for this Question.
Joda-Time 和 java.time 都提供了一个LocalDate
类来处理没有任何时间或时区的仅日期值。只是这个问题的东西。
Joda-Time
乔达时间
We use a DateTimeFormatter
to parse the string by calling parseLocalDate
. If you do not trust your data source, trap for IllegalArgumentException
.
我们使用 aDateTimeFormatter
通过调用来解析字符串parseLocalDate
。如果您不信任您的数据源,请为IllegalArgumentException
.
Here is some code using Joda-Time 2.4.
这是一些使用 Joda-Time 2.4 的代码。
List<LocalDate> list = new ArrayList<LocalDate>();
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
String dates[] = { "05-11-2014" , "23-08-2014" , "05-02-2013" };
for ( String string : dates ) {
LocalDate localDate = formatter.parseLocalDate( string );
list.add( localDate );
}
Collections.sort( list );
Dump to console. Output in original format.
转储到控制台。以原始格式输出。
System.out.println( "list: " + list );
StringBuilder output = new StringBuilder( "Localized sorted list of dates: " );
for ( LocalDate localDate : list ) {
output.append( formatter.print( localDate ) ).append( " | " );
}
System.out.println( output );
When run.
跑的时候。
list: [2013-02-05, 2014-08-23, 2014-11-05]
Localized sorted list of dates: 05-02-2013 | 23-08-2014 | 05-11-2014 |
Or, using the new Java 8 syntax with lambdas. Not really sure if that's an improvement or not.
或者,将新的 Java 8 语法与lambdas 结合使用。不确定这是否是一种改进。
List<LocalDate> list = new ArrayList<>();
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
String[] dateStringsArray = { "05-11-2014" , "23-08-2014" , "05-02-2013" };
List<String> dateStringsList = new ArrayList<>( Arrays.asList( dateStringsArray ) );
dateStringsList.stream().map( ( string ) -> formatter.parseLocalDate( string ) ).forEach( ( localDate ) -> {
list.add( localDate );
} );
Collections.sort( list );
System.out.println( "list: " + list );
StringBuilder output = new StringBuilder( "Localized sorted list of dates: " );
list.stream().forEach( ( localDate ) -> {
output.append( formatter.print( localDate ) ).append( " | " );
} );
System.out.println( output );