tags:

views:

191

answers:

2

I have two Java instances of java.util.Date and I have to find out if they refer to the same day.

I can do this the hard way, taking the dates apart and compare the days, making sure the years match too.

Since this is such a common problem, I expect there to be an easier solution to this problem.

Thanks!

+1  A: 

I use the DateUtils by Apache, it provides the isSameDay(Date,Date) method.

jnt30
If that's the signature and there's no time zone context anywhere else, then it is necessarily broken (or at least restricted to work in an assumed time zone).
Jon Skeet
(The fact that the Javadocs don't even mention which zone is used would make me highly nervous about using that class at all, to be honest. Joda Time is simply a better choice, IMO.)
Jon Skeet
+4  A: 

Instances of java.util.Date refer to instants in time. Which day they fall on depends on which time zone you're using. You could use a java.util.Calendar to represent an instant in a particular time zone...

... or you could use Joda Time instead, which is a much, much better API. Either way, you'll have to know what time zone you're interested in.

In Joda Time, once you've got a relevant time zone, you can convert both instants to LocalDate objects and compare those. (That also means you can compare whether instant X in time zone A is on the same day as instant Y in time zone B, should you wish to...)

Jon Skeet