开发者

How to compare just the day in a java date?

开发者 https://www.devze.com 2023-03-13 18:19 出处:网络
I\'m trying to do a simple date comparison between ye开发者_开发知识库sterday and today if (yesterday.before(today)) {

I'm trying to do a simple date comparison between ye开发者_开发知识库sterday and today

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

The issue is that with the before method I will eval to true even if it's just a few seconds difference. How might I compare just the day (because I only want to eval this to true if it was the previous day (minutes/seconds should be ignored)

Thank you in advance


using DateUtils -

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

EDIT: it can be done without DateUtils as well. See this thread.


If you don't want to use a 3rd party library implement a method like this:

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);
}


If you're up to adding a library that handles dates better than the standard Java libraries, you might want to look at Joda.

Using Joda, you can compute difference between days by:

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

where startDate and endDate are the Joda version of dates, DateTime (actually a superclass of that).

Converting Java Date objects to Joda DateTime objects can be done by a constructor call:

DateTime dateTime = new DateTime(javaDate);

Adding this library may be overkill for this specific problem, but if you deal with date and time manipulation a lot, the library is definitely worth it.


If you want to stick to Date you could temporarily lower your current date by one day. If before() still leads to the same result you have a timespan 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 a deprecated constructor but it should do the job.

0

精彩评论

暂无评论...
验证码 换一张
取 消