Reputation: 2535
I am using the following function in Joda-Time to get difference between two dates:
public static int getDiffYear(Date first) {
int yearsBetween = Years.yearsBetween(new DateTime(first), new DateTime()).getYears();
return yearsBetween;
}
The date supplied to function is: 0001-10-02 (YYYY-MM_DD)
I get the difference as 2013 as checked against today, however I find the correct result should be 2012. Because the day still is 01.
I have a separate function in pure Java, with the desired result:
public static int getDiffYear(Date first) {
Calendar a = Calendar.getInstance();
a.setTime(first);
Calendar b = Calendar.getInstance();
int diff = b.get(Calendar.YEAR) - a.get(Calendar.YEAR);
if (a.get(Calendar.MONTH) > b.get(Calendar.MONTH) ||
(a.get(Calendar.MONTH) == b.get(Calendar.MONTH) && a.get(Calendar.DATE) > b.get(Calendar.DATE))) {
diff--;
}
return diff;
}
Upvotes: 1
Views: 428
Reputation: 3567
Joda will take days into account with yearsBetween
. Try this:
public static int getDiffYear() {
LocalDate firstDate = new LocalDate(1, 10, 2);
LocalDate today = new LocalDate();
int yearsBetween = Years.yearsBetween(firstDate, today).getYears();
return yearsBetween;
}
It will return 2012 as of today (2014/10/01). This indicates something is happening in the conversion from java.util.Date
.
EDIT: This is due to what Marko Topolnik mentioned. When you do new DateTime(first)
you are getting a DateTime
of 0001-09-30.
Upvotes: 2
Reputation: 7655
The Years
utility class is going to only check the difference in years. If you need to keep the days into account, you should use the Days
class and recalculate the result to years.
Upvotes: 1