Get the difference in months for a date.

If you want to know how many months is the difference between 2 dates. Here is the code for you

	public long getDiffMonthsBetweenDates(Date d1, Date d2) {
		if (d2 == null || d1 == null) {
			return -1;//null not accepted
		LocalDate d1Local = Instant.ofEpochMilli(d1.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
		LocalDate d2Local = Instant.ofEpochMilli(d2.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();

		long diffMonths = d1.getTime() > d2.getTime() ? ChronoUnit.MONTHS.between(d2Local, d1Local) : ChronoUnit.MONTHS.between(d1Local, d2Local);
		return diffMonths;

I think the code is self explanatory. Using ChronoUnit.MONTHS.between() we can find the difference between the dates.

Please do note how we use the LocalDate. If you need to handle specific locales, you would have to adjust accordingly.

Leave a Comment