[英]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. 它必须从系统生成。
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.