How to compare only day in java date?

I am trying to make a simple date comparison between yesterday and today

if (yesterday.before(today)) { ... } 

The problem is that using the before method I will evaluate true, even if it is only a few seconds. How can I compare only the day (because I only want this value to be true if it was the previous day (minutes / seconds should be ignored)

Thank you in advance

+4
source share
4 answers

using DateUtils -

 if (!DateUtils.isSameDay(yesterday, today) && (yesterday.before(today)) { //... } 

EDIT: This can be done without DateUtils. See this thread.

+12
source

If you do not want to use a third-party library, execute this method:

 public boolean before(Calendar yesterday, Calendar today) { if(yesterday == today) return false; if(yesterday == null || today == null) return false; return yesterday.get(Calendar.YEAR) < today.get(Calendar.YEAR) ? true : yesterday.get(Calendar.YEAR) == today.get(Calendar.YEAR) && yesterday.get(Calendar.DAY_OF_YEAR) < today.get(Calendar.DAY_OF_YEAR); } 
+5
source

If you want to add a library that handles dates better than standard Java libraries, you can check out Joda .

Using Joda, you can calculate the difference between days:

  Days d = Days.daysBetween(startDate, endDate); int days = d.getDays(); 

where startDate and endDate are versions of Joda, DateTime dates (actually the superclass of this).

Converting Java Date objects to Joda DateTime objects can be done by calling the constructor:

 DateTime dateTime = new DateTime(javaDate); 

Adding this library may be redundant for this particular problem, but if you are dealing with date and time processing, the library is definitely worth it.

+4
source

If you want to stick to Date , you can temporarily lower the current date by one day. If before() still produces the same result, you have a period of time of at least one day.

 final static long DAY_MILLIS = 86400000; Date d1 = new Date(2011, 06, 18); Date d2 = new Date(2011, 06, 16); Date temp = new Date(d1.getTime() - DAY_MILLIS); if (temp.before(d2)) // Do stuff } 

Please note: I used an outdated constructor, but it should do the job.

+3
source

All Articles