I want to compare the date part of two java.util.Date objects. How can I achieve this? I am not looking to comparing the date, month and year separately.
Thanks in advance!
The commons-lang DateUtils provide a nice solution for this problem:
watch this
With this you can compare two Date instances in a single line, loosing sight of every part of the Date you want.
Date date1 = new Date(2011, 8, 30, 13, 42, 15);
Date date2 = new Date(2011, 8, 30, 15, 23, 46);
int compareTo = DateUtils.truncatedCompareTo(date1, date2,
Calendar.DAY_OF_MONTH);
In this example the value of compareTo is 0.
A Date is just an instant in time. It only really "means" anything in terms of a date when you apply a calendar and time zone to it. As such, you should really be looking at Calendar, if you want to stick within the standard Java API - you can create a Calendar object with the right Date and time zone, then set the time components to 0.
However, it would be nicer to use Joda Time to start with, and its LocalDate type, which more accurately reflects what you're interested in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With