英文:
Date comparison in Java not valid
问题
我需要比较包含在ArrayList中的对象的属性“date”。ArrayList中包含的对象属于类型“Books”,每本书都有一个发布日期。日期以String格式给出。
public ArrayList<Book> group;
我已经完成的部分是:
public static Comparator<Book> ComparaisonDate = new Comparator<Book>() {
SimpleDateFormat data = new SimpleDateFormat("dd/MM/yyyy");
@Override
public int compare(Book l1, Book l2) {
try {
return data.parse(l1.launchingDate).compareTo(data.parse(l2.launchingDate));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
};
public void sort(int option) {
Collections.sort(this.group, Book.ComparaisonDate);
}
当我添加两本书的日期为:01/08/2020 和 12/05/2020 时,sort() 函数的结果是:
01/08/2020
12/05/2020
结果应该是:12/05/2020
然后是 01/08/2020
。从我看到的情况来看,它只比较了日期的天,而没有比较月份或年份。你有任何解决这个问题的想法吗?谢谢
英文:
I need to compare the attribute "date" of objects included in an ArrayList.
The objects included in the ArrayList are of type "Books" and each Book has a launching date.
The date is given in a String format.
public ArrayList<Book> group;
What I have done is :
public static Comparator<Book> ComparaisonDate = new Comparator<Book>() {
SimpleDateFormat data = new SimpleDateFormat("dd/mm/yyyy");
@Override
public int compare(Book l1, Book l2) {
try {
return data.parse(l1.launchingDate).compareTo(data.parse(l2.launchingDate));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
};
public void sort(int option) {
Collections.sort(this.group, Book.ComparaisonDate);
}
When I add two books with the dates: 01/08/2020 and 12/05/2020 the result of the sort() function is:
01/08/2020
12/05/2020
The result should be: 12/05/2020
and then 01/05/2020
.From what I can see, it compares only the day and not the month or year. Do you have any idea how to fix this? thanks
答案1
得分: 3
mm
在模式中代表小时的分钟部分,因此排序实际上是正确的。您需要使用MM
。请参阅 https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html 获取有效的模式信息。
英文:
mm
in the pattern stands for Minutes of the Hour, therefore the sorting is actually correct. You need MM
. See https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html for valid patterns.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论