java - 如何将集合集合的项目与当前日期进行比较?

标签 java dataset set hashset

我有以下集合,需要将其日期实例与当前日期进行比较。虽然两个日期相同但比较返回 false !!

MyClass.java

import java.util.Date;
public class MyClass {
   private Date date;

   ...

}

我的代码

 ....
 Set <MyClass> myclass = new HashSet();

 I populate it with some data here...

 for(MyClass m : myclass)
 {
   System.err.println("date>>:" + trim(m.getDate()));  //returns 2013-08-08
   System.err.println("date>>:" + trim(getCurrentDate()));  //returns 2013-08-08
   System.err.println("boolean:" +                            
               trim(m.getDate()).equals(trim(getCurrentDate()))); //returns false
 }
}

 public Date getCurrentDate() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    dateFormat.format(date));
    return date;
}

public Date trim(Date date){
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.HOUR, 0);
    return calendar.getTime();
}

最佳答案

日期不一样,它们可能相差毫秒/秒。 Date equals 不依赖于日期的格式,而是比较值。下面的代码也会返回 false:

Date d1 = new Date();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
        Date d2 = new Date();
        f.format(d2);
        System.out.println(d1);//e.g. Thu Aug 08 12:09:24 IST 2013
        System.out.println(d2);//e.g. Thu Aug 08 12:09:26 IST 2013
        System.out.println(d1.equals(d2));//false

Date.equals 比较时间(Date.getTime()),equals只有在以下情况下才会返回true他们匹配:

public boolean equals(Object obj) {
        return obj instanceof Date && getTime() == ((Date) obj).getTime();
    }

根据 javadoc:

 The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object. 

Thus, two Date objects are equal if and only if the getTime method returns the same long value for both. 

Date.getTime 返回自格林威治标准时间 1970 年 1 月 1 日 00:00:00 以来的毫秒数

因此,在您使用 trim 更新问题时,假设您正在比较两个 long 时间值(以毫秒为单位)。

如果您需要比较两个不同 date 实例的 yyyy-MM-dd 值,请考虑改用 String.equals(hack 方式):

SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String date1 = f.format(new Date());//2013-08-08
        String date2 = f.format(new Date());//2013-08-08
        System.out.println(date1.equals(date2));

关于java - 如何将集合集合的项目与当前日期进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18119375/

相关文章:

java - 如何在初始化后将Java对象设置为final

algorithm - 检测数据变化的最佳哈希函数?

c++ - std::transform 如何不返回(而不是抛出),只是跳过?

parallel-processing - 在插入符中设置种子平行随机森林以获得可重现的结果

java - Spring Batch 在处理每个批处理后是否释放堆内存?

java - 在 Java 中使用 Arrays.sort() 时出现错误

c# - 我们可以将数据集传递给 Web 服务方法吗?如果是,那么如何?

python - 从屏蔽的二维数组中提取平均值

c++ - 使用非默认比较谓词的集合容器

java - 阻塞 'take()' 但有驱逐政策的队列实现