[英]Most efficient way of checking if Date object and Calendar object are in the same month
[英]What's the most efficient way to sort lists of date, week and month?
//dd/mm/yyyy
list<String> datesList
//weeks of year
list<int> weeksList
//month
list<int> monthsList
我想按升序对它们进行排序,最有效的方法是什么? (尤其是日期列表,它是一个字符串列表,其中每个项目的条目均为dd / mm / yyyy)。
由于没有人发布它,因此我必须: Collections.sort 。
对于日期,如eumiro所建议,最简单的方法可能是将其转换为Date对象,然后进行排序。
java.util.List<String> dates = Arrays.asList("05/07/2010", "12/12/1984", "28/01/2008");
System.out.println("unsorted dates = " + dates);
Collections.sort(dates, new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
String y1 = o1.substring(6, 10);
String y2 = o2.substring(6, 10);
if (y1.equals(y2))
{
String m1 = o1.substring(3, 5);
String m2 = o2.substring(3, 5);
if (m1.equals(m2))
{
return m1.compareTo(y2);
}
String d1 = o1.substring(0, 2);
String d2 = o2.substring(0, 2);
return d1.compareTo(d2);
}
return y1.compareTo(y2);
}
});
System.out.println("sorted dates = " + dates);
这是如何做:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class DateSortExample
{
public static void main(String[] args)
{
DateFormat format = new SimpleDateFormat("yyyy-MMM-dd");
List<Date> values = new ArrayList<Date>();
for (String arg : args)
{
try
{
Date value = format.parse(arg);
values.add(value);
}
catch (ParseException e)
{
e.printStackTrace();
}
}
System.out.println("before sort: " + values);
Collections.sort(values);
System.out.println("after sort: " + values);
}
}
输出如下:
before sort: [Mon Oct 18 00:00:00 EDT 2010, Mon Jan 04 00:00:00 EST 1999, Wed Dec 25 00:00:00 EST 1968]
after sort: [Wed Dec 25 00:00:00 EST 1968, Mon Jan 04 00:00:00 EST 1999, Mon Oct 18 00:00:00 EDT 2010]
创建一个比较器,将比较之前的每个字符串日期转换为日期对象。
List<String> dates = Arrays.asList("05/07/2010", "12/12/1984", "28/01/2008");
final DateFormat fmt = new SimpleDateFormat("dd/mm/yyyy");
Collections.sort(dates, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
try {
return fmt.parse(o1).compareTo(fmt.parse(o2));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
});
System.out.println(dates);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.