0
votes

I need to calculate in Java the number of months between two Date objects, but only for the ones which are in the given year.

For example:

01.04.2013 - 30.07.2013, year=2013 => result=4

01.10.2013 - 30.02.2014, year=2013 => result=3

For the second example the result is 3, because only October, November and December are in the given year, 2013. The rest of the months are in 2014.

01.10.2012 - 30.02.2014, year=2013 => result=12

I have this code, but id doesn't work for the following case 01.04.2013 - 30.07.2013, year=2012 => result=0

        Calendar startCalendar = new GregorianCalendar();
        startCalendar.setTime(c.getStartDate());
        Calendar endCalendar = new GregorianCalendar();
        endCalendar.setTime(c.getEndDate());


        Calendar calculatedStartDate = new GregorianCalendar();
        Calendar calculatedEndDate = new GregorianCalendar();

        if (startCalendar.get(Calendar.YEAR) < year) {
            calculatedStartDate.setTime(new GregorianCalendar(year, Calendar.JANUARY, 1).getTime());
        }
        else {
            calculatedStartDate.setTime(c.getStartDate());
        }

        if (endCalendar.get(Calendar.YEAR) > year) {
            calculatedEndDate.setTime(new GregorianCalendar(year, Calendar.DECEMBER, 31).getTime());
        }
        else {
            calculatedEndDate.setTime(c.getEndDate());
        }

        int diffMonth = calculatedEndDate.get(Calendar.MONTH) - calculatedStartDate.get(Calendar.MONTH);
        return diffMonth + 1;
1
show what you done. we can help you.. if you found any issues? We are not here to do your homework.Dilip Kumar
Actually, some of us are here to do your homework. Asking to solve homework questions isn't forbidden.Mark
This is not even a homework, I don't know who would even give such problem as homework. I added the code I've got, removing the business context. Still don't get why people who don't know the answer rate this question as negative.Soreena
Just to put my 2 cents in: the biggest time period which is regular is a week (just like an hour, a minute, a second). The month is the smallest time period which is irregular. Whenever i have to measure time 'distances' (e.g. in countdowns on my site) i like to do it using weeks exactly because of this. When you say X months you don't know exactly how many weeks, but when you say X weeks you know exactly how many days that is (maybe this doesn't help you, just wanted to point it out :)Sandman

1 Answers

0
votes

Check if the second date is of the same year of first; then if this condition is false, set the second date with "31/12/year" and calculate the number of months.

For example:

first date: 31/4/2014
second date: 28/7/2014
2014 > 2014: false, so
    7-4 = 3 + 1 = 4 months

first date: 31/4/2014
second date: 28/7/2015
2015 > 2014: true, so
    second date = 31/12/2014
    12-4 = 8 + 1 = 9 months