Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing dates in Java - only years, months and days

Tags:

java

date

I'm trying to compare to dates object. Only one problem is that I want to compare just days, month and years.

/* toString output
mydate 2013-08-23
current date: Thu Aug 23 14:15:34 CEST 2013

If I compare just days ( 23-08-2013 ) dates are equal, if I'm using .after() .before() methods dates are diffrent.

Is there is Java method that compares only days, month, years in easy way or do I have to compare each value ?

like image 992
kingkong Avatar asked Aug 23 '13 12:08

kingkong


2 Answers

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

This will work perfectly.........

like image 198
piyush Avatar answered Sep 21 '22 16:09

piyush


Joda-Time is much better and highly recommended. But if you have to use Java api, you can do-

Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();

c1.setTime(someDate);
c2.setTime(someOtherDate);

int yearDiff = c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
int monthDiff = c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
int dayDiff = c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH);

Say to compare only year, you can do-

if(c1.get(Calendar.YEAR) > c2.get(Calendar.YEAR)){
    // code
}

etc.

like image 28
Sajal Dutta Avatar answered Sep 23 '22 16:09

Sajal Dutta