tags:

views:

227

answers:

3

I'm trying to work with a timeseries of monthly data. That is, there is a value for each month, and no specific date (or time) associated with it.

I could have arbitrarily fixed the day, time at some constant (eg midnight on first of the month) then used a java.util.date or joda DateTime but decided to try and do this within the joda type system.

My first step was to create a YearMonth class which extends AbstractPartial (by analogy to LocalDate). I've now reached the next step of trying to increment a YearMonth by a number of months. I could write the code myself (adding % 12) but I'd rather use a Joda style way of doing this.

What code should I write, and where should it live so I can for example add a 13 month or 2 year Period to my YearMonth class? Or am I going down a bad track?

+1  A: 

Year/Month math has to be done as follows:

ym = (year*12+month)

Do your math on ym.  Add months or years, or whatever

year = ym / 12
month = ym % 12

There's no real alternative. This is provably correct and no alternative will actually be simpler. Some languages (like Python) have a divmod function that combines the last two lines of code, but that doesn't change the essence.

You have units (months) that you will display to people as year-month. It might as well be Yards-Feet or Hours-Minutes or any other simple conversion to a two-part base.

S.Lott
I understand the math. Joda seems to go to a lot of effort to have a Chronology which separates out the knowledge that there are 12 months in a year. Are you making the case that using this is a waste of time? The only case I can think of where it adds values is moving to a calendar which has 13 months, or a non-even number of months per year (Lunar?) but this is probably a case for YAGNI
Nick Fortescue
Depends on which calendars you plan to support. The Gregorian calendar is pretty popular and has a fixed year/month relationship. Other calendars, are not so simple. Will you ever support a non-Gregorian calendar? Or are you worried that someone may try to change the Gregorian calendar?
S.Lott
Also, you have a bunch of class-level fields (i.e. `months`) that may contain the relevant "12" constant.
S.Lott
+1  A: 

The joda-time svn has a YearMonth class, ready for v2.0.

JodaStephen
Thanks - any ETA on v2? I'll have a look.
Nick Fortescue
Classic OSS answer - When its finished :-)
JodaStephen
A: 

DateTime currentInstant = new DateTime();

// add a month

currentInstant = currentInstant.plusMonths(1);

// add 2Y + 13M => 3Y 1M

Period incPeriod = new Period().plusYears(2).plusMonths(13);

currentInstant = currentInstant.plus(incPeriod);

lkw
Sorry, this doesn't answer the question. It says how to add years and months to a DateTime. There are good reasons to have a class which only knows about years and months.
Nick Fortescue