Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing if two Date instances refer to the same day

Tags:

java

datetime

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!

like image 519
raoulsson Avatar asked Feb 28 '23 07:02

raoulsson


2 Answers

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

like image 122
Jon Skeet Avatar answered Mar 16 '23 00:03

Jon Skeet


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.

like image 32
jnt30 Avatar answered Mar 15 '23 23:03

jnt30