Example: given a continuous list of date range
List[0] = from 2001 Jan 01 to 2001 Aug 14
List[1] = from 2001 Aug 15 to 2002 Jul 10
Let’s assume that a financial year is from 1st of July to 30th of June (of next year) so the output should be
AnotherList[0] = from 2000 Jul 01 to 2001 Jun 30
period: 2001 Jan 01 to 2001 Jun 30AnotherList[1] = from 2001 July 01 to 2002 Jun 30
period: 2001 Jul 01 to 2001 Aug 14 period: 2001 Aug 15 to 2002 Jun 30AnotherList[2] = from 2002 July 01 to 2003 Jun 30
period: 2002 Jul 01 to 2002 Jul 10
Again it’s very easy to work out by hand but my method contains close to 100 lines of code with the combination of if else, for each and while loops which I think it’s ugly. I am trying to simplify the algorithm so that it’s easier to maintain and debug. Thanks in advance.
EDIT: Changed to include clearer requirements.
Given a list that contains contiguous date ranges, the code doesn’t have to be hard at all. In fact, you don’t even have to write an actual loop:
This assumes some
DateRangestructures and helper functions, like this:This test code:
outputs:
from 2000 Jul 01 to 2001 Jun 30 period: 2001 Jan 01 to 2001 Jun 30 from 2001 Jul 01 to 2002 Jun 30 period: 2001 Jul 01 to 2001 Aug 14 period: 2001 Aug 15 to 2002 Jun 30 from 2002 Jul 01 to 2003 Jun 30 period: 2002 Jul 01 to 2002 Jul 10