在Java中日期比较无效。

huangapple go评论93阅读模式
英文:

Date comparison in Java not valid

问题

我需要比较包含在ArrayList中的对象的属性“date”。ArrayList中包含的对象属于类型“Books”,每本书都有一个发布日期。日期以String格式给出。

  1. public ArrayList<Book> group;

我已经完成的部分是:

  1. public static Comparator<Book> ComparaisonDate = new Comparator<Book>() {
  2. SimpleDateFormat data = new SimpleDateFormat("dd/MM/yyyy");
  3. @Override
  4. public int compare(Book l1, Book l2) {
  5. try {
  6. return data.parse(l1.launchingDate).compareTo(data.parse(l2.launchingDate));
  7. } catch (ParseException e) {
  8. throw new IllegalArgumentException(e);
  9. }
  10. }
  11. };
  12. public void sort(int option) {
  13. Collections.sort(this.group, Book.ComparaisonDate);
  14. }

当我添加两本书的日期为:01/08/2020 和 12/05/2020 时,sort() 函数的结果是:

  1. 01/08/2020
  2. 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.

  1. public ArrayList&lt;Book&gt; group;

What I have done is :

  1. public static Comparator&lt;Book&gt; ComparaisonDate = new Comparator&lt;Book&gt;() {
  2. SimpleDateFormat data = new SimpleDateFormat(&quot;dd/mm/yyyy&quot;);
  3. @Override
  4. public int compare(Book l1, Book l2) {
  5. try {
  6. return data.parse(l1.launchingDate).compareTo(data.parse(l2.launchingDate));
  7. } catch (ParseException e) {
  8. throw new IllegalArgumentException(e);
  9. }
  10. }
  11. };
  12. public void sort(int option) {
  13. Collections.sort(this.group, Book.ComparaisonDate);
  14. }

When I add two books with the dates: 01/08/2020 and 12/05/2020 the result of the sort() function is:

  1. 01/08/2020
  2. 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.

huangapple
  • 本文由 发表于 2020年10月13日 03:10:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64323992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定