Sanjana
Sanjana

Reputation: 467

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 ;
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.

PS#I am not allowed to use Joda Time library.

UPDATE- Is there any other way to compare shippingDate with current Date. I don't want to hardcode the current date using SimpleDateFormat. It has to be generated from system.

Upvotes: 1

Views: 248

Answers (3)

Rupesh
Rupesh

Reputation: 2667

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.

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

Upvotes: 0

ssantos
ssantos

Reputation: 16526

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

Calendar g = new GregorianCalendar();

and

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

Upvotes: 1

NPE
NPE

Reputation: 500187

The Javadoc gives a clue (emphasis mine):

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.

Upvotes: 5

Related Questions