Best Solution:
If you already have java.sql.Date
instances then
final Date d1 = new java.sql.Date(2017 - 1900, 12, 8);
final Date d2 = new java.sql.Date(2022 - 1900, 07, 31);
I know that I am using a deprecated constructor in java.sql.Date
, that is just for convenience to get what I need in the least amount of lines of code.
Never use this constructor in production code!
The simplest most straightforward self documenting way to get what you want:
final long monthsBetween ChronoUnit.MONTHS.between(d1.toLocalDate(),d2.toLocalDate()) + 1;
Because with this method you do not have to twiddle with TimeZone
information because it is all guaranteed to be correct for instances of LocalDate
created this way.
For some reason only java.sql.Date
only has .toLocalDate()
which is good for you because that is what you get back from the database.
public LocalDate toLocalDate()
Converts this Date object to a
LocalDate The conversion creates a LocalDate that represents the same
date value as this Date in local time zone
Returns: a LocalDate object representing the same date value
Since:
1.8
Comments on corrections to your code:
The correct formula is:
(y2 - y1) * 12 + (m2 - m1) + 1
Also, your code is overly complex and using very old classes.
Java 8 Solution and your Java 7 compatible corrected solution:
public class Q47717075
{
/*
https://stackoverflow.com/questions/1086396/java-date-month-difference
*/
public static void main(@Nonnull final String[] args)
{
final Date d1 = new java.sql.Date(2017 - 1900, 12, 8);
final Date d2 = new java.sql.Date(2022 - 1900, 07, 31);
System.out.println(CalcDateDiff(d1, d2));
/* Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z. */
System.out.println(intervalInMonths(LocalDate.of(2017,12,8), LocalDate.of(2022,7,31)));
System.out.println(ChronoUnit.MONTHS.between(d1.toLocalDate(),d2.toLocalDate()) + 1);
}
/*
Alternate Java 8 version
*/
public static int intervalInMonths(@Nonnull final LocalDate i1, @Nonnull final LocalDate i2)
{
final Period p = Period.between(i1, i2);
return (p.getYears() * 12) + p.getMonths() + 1;
}
/**
* Your versin corrected
*/
public static int CalcDateDiff(@Nonnull final Date date1, @Nonnull final Date date2)
{
final Calendar d1 = Calendar.getInstance();
d1.setTime(date1);
final Calendar d2 = Calendar.getInstance();
d2.setTime(date2);
return ((d2.get(YEAR) - d1.get(YEAR)) * 12 + (d2.get(MONTH) - d1.get(MONTH)) + 1);
}
}
The Correct Output is:
56
56
56