Akyo
Akyo

Reputation: 149

Joda-Time : Date calculation

I would like to calculate precisely the months between two dates to achieve this I do something like :

            DateTimeZone ZONE = DateTimeZone.forID("Europe/London");
            String DATE_FORMAT = "dd/MM/yyyy";
            DateTimeFormatter FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT).withZone(ZONE);
            LocalDate dateTime = FORMATTER.parseLocalDate("28/05/2013");
            LocalDate dateTime6MonthAfter = FORMATTER.parseLocalDate("28/02/2014");
            Period todayUntilEndOfContract = new Period(dateTime,dateTime6MonthAfter);
            todayUntilEndOfContract.getMonths() +"M/"+ todayUntilEndOfContract.getWeeks() +"W/"+ todayUntilEndOfContract.getDays() +"D/");

So this give me precisely 9 month between 28/05/2013 and 28/02/2014 BUT!!! when I calculate the dates (29, 30, 31)/05/2013 with 28/02/2014 it always give me 9 month normally it should say 8M/3W/(6,5,4)D/ why is it always 9M/0W/0D please...?

Thanks a lot

Upvotes: 0

Views: 200

Answers (1)

user1596371
user1596371

Reputation:

Your issue is that you are expecting something a little different than what is provided. If I ask you the question "what is 30th January plus one month?" then there are a number of different answers which are valid under different assumptions. In Joda's case the answer is "28th February" (or 29th if a leap year).

Although you are asking for month-based information I would suggest that you obtain the number of days instead and use that as a basis, as it is probably closer to what you need:

int days = Days.daysBetween(dateTime, dateTime6MonthAfter).getDays();

You can always use this number to feed back in to your code and obtain different values to fit your requirements.

Upvotes: 2

Related Questions