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 ?
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.........
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With