I have the following code and trying to figure out if the date difference is greater than one year or not. If I have the two dates like this:
2022-08-20 10:26:44.000
2023-08-25 10:26:44.000
How should I send these two dates such that it's accepted for moreTheOneYearDifference method as defined below?
public class DateOneYearDifferenceTest {
final GregorianCalendar gc = new GregorianCalendar();
public static void main(String[] args) {
System.out.printf(moreTheOneYearDifference(2022-08-20 10:26:44.000, 2023-08-25 10:26:44.000));
}
public boolean moreTheOneYearDifference(Calendar c1, Calendar c2) {
int days = 365;
if (c1.before(c2) && gc.isLeapYear(c1.get(Calendar.YEAR))) {
days += 1;
} else if (gc.isLeapYear(c2.get(Calendar.YEAR))) {
days += 1;
}
return TimeUnit.MICROSECONDS.toDays((long) Math.abs(c1.getTimeInMillis() - c2.getTimeInMillis())) >= days;
}
}
The above method was copied from this stackoverflow post answer
You can send like this:
I corrected the month values to be 0-based (January is 0, February is 1, and so on), and created instances of
Calendarfordate1anddate2using theGregorianCalendarclass and provided the correct year, month, day, hour, minute, and second values.Note: I think that you mean moreThanOneYearDifference and no moreTheOneYearDifference
You can do this way:
But, like Basil Bourque said: "These terrible date-time classes were years ago supplanted by the modern java.time classes defined in JSR 310."
So, I recommend that you use the modern java.time classes if it is possible. It will be something like this:
I don't know how much specific you need to be, so maybe you should edit it to consider hours, minutes, seconds, etc...