1

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

2
  • 1
    @libik That's in the Date class. Commented Oct 12, 2013 at 18:20
  • Just print new Date() back to back, and you will get the idea. Commented Oct 12, 2013 at 18:20

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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()))

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.