Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get date part (dispose of time part) from java.util.Date?

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!

like image 475
MozenRath Avatar asked Dec 22 '22 08:12

MozenRath


2 Answers

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.

like image 102
Turbokiwi Avatar answered Dec 23 '22 21:12

Turbokiwi


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.

like image 44
Jon Skeet Avatar answered Dec 23 '22 20:12

Jon Skeet