0

In a tutorial I am watching,I am trying to calculate the difference between two dates. I need the initMonth and the finishMonth with the idea being to subtract the initMonth from the finishMonth and calculate the difference.

I can do something like this using the Calendar class(and then something similar with the finishMonth):

int initMonth = calendar.get(Calendar.MONTH);

...but the problem is that if the initMonth is May(for example) and the endMonth is January; when I subtract the endMonth from the initMonth I will get 1-5=-4--and I will have a negative difference. In order to solve this problem, the instructor came with the solution of multiplying the YEAR * 12 and then adding the month like this:

int initMonth = calendar.get(Calendar.YEAR) *12 + calendar.get(Calendar.MONTH);

However, this doesn't make any sense to me since the year will return something like 2021 * 12 + month to some extremely large number. My guess was that he meant MONTH so then we will get the months in the year plus the month. Would I be correct? I'm unsure, and wanted to confirm this logic.

Thank you in advance.

CodingChap
  • 1,088
  • 2
  • 10
  • 23
  • 1
    You may want to use the java.time API instead of `java.util.Date`. – dan1st May 22 '21 at 06:14
  • Also have a look at https://stackoverflow.com/questions/48950145/java-8-calculate-months-between-two-dates – Seelenvirtuose May 22 '21 at 07:44
  • 2
    Instructors suggesting to use `Calendar` in 2021 deserve to be sacked. That class is *so* poorly designed and *so* outdated. – Ole V.V. May 22 '21 at 09:03
  • Under the linked original question look into [the answer by Basil Bourque](https://stackoverflow.com/a/42895017/5772882) and [the one by Roland Tepp](https://stackoverflow.com/a/34811261/5772882) using java.time, the modern Java date and time API. If I understand correctly these match your requirement better than [the one by Kuchi](https://stackoverflow.com/a/28147750/5772882) also using java.time. – Ole V.V. May 22 '21 at 09:07

1 Answers1

1

Your tutorial is obsolete by several years. Never use Calendar or Date class. Use only java.time classes.

Apparently you want to calculate elapsed months.

LocalDate then = LocalDate.of( 2020 , Month.MARCH ) ;
LocalDate today = LocalDate.now() ;
Period elapsed = Period.between ( then , today ) ;
int months = elapsed.toMonths() ;

Search Stack Overflow to learn more. This has been covered many times already.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • If you think that "this has been covered many times already", shouldn't you mark this question as a duplicate instead of answering it? (Especially as an experienced SO user as you are with 217k rep?) – Seelenvirtuose May 22 '21 at 07:43