File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes java.util.Date problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "java.util.Date problem" Watch "java.util.Date problem" New topic
Author

java.util.Date problem

Ronnie Ho
Ranch Hand

Joined: Aug 10, 2005
Posts: 47

Results:
false
1127793600000
1127793600000

Both beginDate and selectedDate are of type java.util.Date. Can someone explain the result? According to the API:

two Date objects are equal if and only if the getTime method returns the same long value for both.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Well, where do the Date objects come from?


[Jess in Action][AskingGoodQuestions]
Ronnie Ho
Ranch Hand

Joined: Aug 10, 2005
Posts: 47
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

You'd think. The one from the database is probably a java.sql.Date, which is a subclass of java.util.Date. Still, they should compare equal if getTime() reports the same number.
Bimal Patel
Ranch Hand

Joined: Aug 29, 2003
Posts: 130
Hi,

Can you try using compareTo(<Date object> . If the result is 0, the two dates are equal. I don't know why equal is not working . This may help you.


Work Hard, Expect The Worst...<br /> <br />Bimal R. Patel<br />(SCJP 1.2, SCWCD 1.4)
Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
There are two possible alternatives to this:

a. Create calendar objects and compare the relevant fields of the calendar instances (day, month, year...).

b. Change the code to something like

int tolerableDifference = 24 * 60 * 60 * 1000; // milliseconds
return Math.abs(beginDate.getTime() - selectedDate.getTime()) < tolerableDifference;

Here, it should return true only if they represent the same date upto the day. (Caution: This algorithm might need some testing/debugging thow.)

Perhaps the first one is preferable.

Hope this helps.


ASCII silly question, Get a silly ANSI.
Akshay Kiran
Ranch Hand

Joined: Aug 18, 2005
Posts: 220
I don't know why your code is not working, but I can offer a workaround.

Just try
Date begindate2= new Date(beginDate.getTime());

and then

selectedDate.equals(begindate2);


"It's not enough that we do our best; sometimes we have to do<br />what's required."<br /> <br />-- Sir Winston Churchill
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: java.util.Date problem