Comparing Two Java.Util.Dates to See If They Are in the Same Day

Comparing two java.util.Dates to see if they are in the same day

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);

Note that "same day" is not as simple a concept as it sounds when different time zones can be involved. The code above will for both dates compute the day relative to the time zone used by the computer it is running on. If this is not what you need, you have to pass the relevant time zone(s) to the Calendar.getInstance() calls, after you have decided what exactly you mean with "the same day".

And yes, Joda Time's LocalDate would make the whole thing much cleaner and easier (though the same difficulties involving time zones would be present).

How to check if 2 dates are on the same day in Java

Although given answers based on date component parts of a java.util.Date are sufficient in many parts, I would stress the point that a java.util.Date is NOT a date but a kind of UNIX-timestamp measured in milliseconds. What is the consequence of that?

Date-only comparisons of Date-timestamps will depend on the time zone of the context. For example in UTC time zone the date-only comparison is straight-forward and will finally just compare year, month and day component, see other answers (I don't need to repeat).

But consider for example the case of Western Samoa crossing the international dateline in 2011. You can have valid timestamps of type java.util.Date, but if you consider their date parts in Samoa you can even get an invalid date (2011-12-30 never existed in Samoa locally) so a comparison of just the date part can fail. Furthermore, depending on the time zone the date component can generally differ from local date in UTC zone by one day, ahead or behind, in worst case there are even two days difference.

So following extension of solution is slightly more precise:

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
fmt.setTimeZone(...); // your time zone
return fmt.format(date1).equals(fmt.format(date2));

Similar extension also exists for the more programmatic approach to first convert the j.u.Date-timestamp into a java.util.GregorianCalendar, then setting the time zone and then compare the date components.

How to know if a Date is within the same day of other date

Why don't you use DateUtils?

You can directly invoke methods like isSameDay

if (DateUtils.isSameDay(date1, date2)) {
System.out.println("Same Date");
} else if (date1.before(date2)) {
System.out.println("date1 before date2");
} else {
System.out.println("date1 after date2");
}

Check Apache DateUtils.

How to compare dates in Java?

Date has before and after methods and can be compared to each other as follows:

if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}

For an inclusive comparison:

if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}

You could also give Joda-Time a go, but note that:

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

Back-ports are available for Java 6 and 7 as well as Android.

java - how to compare same days in date

use the joda api.

http://joda-time.sourceforge.net/

Its a lot easier and better than the Calendar object route in java jdk

How to compare two Dates without the time portion?

Update: while Joda Time was a fine recommendation at the time, use the java.time library from Java 8+ instead where possible.


My preference is to use Joda Time which makes this incredibly easy:

DateTime first = ...;
DateTime second = ...;

LocalDate firstDate = first.toLocalDate();
LocalDate secondDate = second.toLocalDate();

return firstDate.compareTo(secondDate);

EDIT: As noted in comments, if you use DateTimeComparator.getDateOnlyInstance() it's even simpler :)

// TODO: consider extracting the comparator to a field.
return DateTimeComparator.getDateOnlyInstance().compare(first, second);

("Use Joda Time" is the basis of almost all SO questions which ask about java.util.Date or java.util.Calendar. It's a thoroughly superior API. If you're doing anything significant with dates/times, you should really use it if you possibly can.)

If you're absolutely forced to use the built in API, you should create an instance of Calendar with the appropriate date and using the appropriate time zone. You could then set each field in each calendar out of hour, minute, second and millisecond to 0, and compare the resulting times. Definitely icky compared with the Joda solution though :)

The time zone part is important: java.util.Date is always based on UTC. In most cases where I've been interested in a date, that's been a date in a specific time zone. That on its own will force you to use Calendar or Joda Time (unless you want to account for the time zone yourself, which I don't recommend.)

Quick reference for android developers

//Add joda library dependency to your build.gradle file
dependencies {
...
implementation 'joda-time:joda-time:2.9.9'
}

Sample code (example)

DateTimeComparator dateTimeComparator = DateTimeComparator.getDateOnlyInstance();

Date myDateOne = ...;
Date myDateTwo = ...;

int retVal = dateTimeComparator.compare(myDateOne, myDateTwo);

if(retVal == 0)
//both dates are equal
else if(retVal < 0)
//myDateOne is before myDateTwo
else if(retVal > 0)
//myDateOne is after myDateTwo

Comparing if two Date instances refer to the same day

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

Compare two dates in Java

Date equality depends on the two dates being equal to the millisecond. Creating a new Date object using new Date() will never equal a date created in the past. Joda Time's APIs simplify working with dates; however, using the Java's SDK alone:

if (removeTime(questionDate).equals(removeTime(today)) 
...

public Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}


Related Topics



Leave a reply



Submit