MxyL MxyL - 3 months ago 17
Java Question

Comparing date periods and date period lengths

Suppose I have some bills with some start dates and end dates.

Mar 10 to Apr 9
Apr 10 to May 9
May 10 to Jun 9


The business rule that I want to check is that

for any given bill, the previous bill is exactly one period behind


So for example, Mar 10 to Apr 9 is about a month apart, and so I use that to check that any two consecutive bill start dates (Apr 10 vs Mar 10) are about a month apart.

Now the problem I'm having is obtaining the length of the period. For example, suppose I have the following data set

Jan 1 to Jan 31
Feb 1 to Feb 28
Mar 1 to Mar 31


I am using JodaTime library, so I say something like

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime date1 = formatter.parseDateTime("01/01/2013");
DateTime date2 = formatter.parseDateTime("31/01/2013");
System.out.println(Months.monthsBetween(date1, date2).toPeriod().getMonths());


And that returns 0, which is correct, but not useful.

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime date1 = formatter.parseDateTime("31/01/2013");
DateTime date2 = formatter.parseDateTime("01/02/2013");
System.out.println(Months.monthsBetween(date1, date2).toPeriod().getMonths());


And that returns 1, even though it's a day apart.

What is a better way to do this? I can check days difference but since the billing periods are specified in months I would like any output to be consistent (eg: these bills are not x months apart, etc)

Answer

why not just check the the start date of one period minus one day is equal to the end date of the previous period?

LocalDate endDate1, startDate2...

startDate2.minusDays(1).equals(endDate1)