简体   繁体   English

使用equals比较Java中的日期

[英]Comparing Dates in java using equals

* UPDATE *I have an instance in my class java.util.Date shippingDate which I need to compare whether it is equal to current date or not. * 更新 *我在类java.util.Date shippingDate有一个实例,我需要比较它是否等于当前日期。

java.util.Date shippingDate ;
Calendar g = new GregorianCalendar();
shippingDate=g.getTime();
if(shippingDate.equals(new Date()))
{
System.out.println("Match found");
}

Equals is overridden in Date, so it should execute the sysout.But its not printing anything. Equals在Date中被覆盖,因此它应该执行sysout.But不打印任何内容。

PS#I am not allowed to use Joda Time library. PS#我不允许使用Joda Time库。

UPDATE- Is there any other way to compare shippingDate with current Date. 更新-还有其他方法可以将shippingDate与当前Date进行比较。 I don't want to hardcode the current date using SimpleDateFormat . 我不想使用SimpleDateFormat对当前日期进行硬编码。 It has to be generated from system. 它必须从系统生成。

The Javadoc gives a clue (emphasis mine): Javadoc提供了一个线索(重点是我的):

public Date()

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond . 分配一个Date对象并对其进行初始化,以便它表示分配给它的时间以最近的毫秒为单位)

When you create a new Date object, it takes the current time of the system, so both dates actually differ in the milliseconds passed between lines 当创建一个新的Date对象时,它占用系统的当前时间,因此两个日期实际上在行之间传递的毫秒数上有所不同

Calendar g = new GregorianCalendar();

and

if(shippingDate.equals(new Date()))

have you noticed that you have two lines and at line 1 you get calendar object and you compare the same with date object at line 2 , understand that there is millisecond difference between execution time of both two so it would never be same. 您是否注意到有两行,并且在line 1获得了日历对象,并在line 2其与date对象进行了比较,请理解,两者的执行时间之间存在毫秒差,所以它永远不会相同。

java.util.Date shippingDate ;
Calendar g = new GregorianCalendar(); //line 1
shippingDate=g.getTime();
if(shippingDate.equals(new Date())) //line 2
{
System.out.println("Match found");
}

The result would never be equal if you try to compare two different objects created in multiple statements. 如果您尝试比较在多个语句中创建的两个不同的对象,则结果永远不会相等。


Addressing to your question in update : get time in milliseconds using shippingDate.getTime() and then to compare this with system time use System.currentTimeMillis() or you can also use System.nanoTime() but the result would never be same 在更新中解决您的问题 :使用shippingDate.getTime()以毫秒为单位获取时间,然后使用System.currentTimeMillis()与系统时间进行比较,或者也可以使用System.nanoTime() 但结果永远不会相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM