4

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!

raoulsson
  • 14,978
  • 11
  • 44
  • 68

3 Answers3

6

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

I use the DateUtils class by Apache Commons Lang 2, it provides the isSameDay(Date,Date) method.

Update:

Here the link to Apache Commons Lang 3.

t0r0X
  • 4,212
  • 1
  • 38
  • 34
jnt30
  • 1,367
  • 2
  • 15
  • 21
  • 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 Sep 10 '09 at 16:56
  • (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 Sep 10 '09 at 16:59
0

From elsewhen on StackOverflow

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));
Community
  • 1
  • 1
Ken Scott
  • 1
  • 1
  • 2