Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

I have 2 Date variables, Date1 and Date2. I want to check if Date 1 fall on the same date as Date2 (but they are allowed to have different times).

How do i do this?

It looks like a really easy thing to do, but i'm struggling.

EDIT: I want to avoid external libraries and stuff

EDIT: My orgional idea was to remove the hour, min, sec but those features are marked as depreciated in Java. So what should I use????

like image 790
Yahya Uddin Avatar asked Mar 16 '14 16:03

Yahya Uddin


2 Answers

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.

like image 61
Meno Hochschild Avatar answered Oct 04 '22 03:10

Meno Hochschild


Why don't you simply compare the year, month and day? You can write your method for doing it something like:

private boolean isDateSame(Calendar c1, Calendar c2) {
    return (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && 
            c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) &&
            c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH));
}
like image 39
Sourabh Bhat Avatar answered Oct 04 '22 04:10

Sourabh Bhat