2

I'm using the Joda Time library to subtract one month from a LocalDate:

LocalDate date = new LocalDate(2013, 3, 31);
System.out.println(date.minusMonths(1));

The result is 2013-02-28, which is what I would intuitively expect and which is also documented in the API:

If subtracting months makes the day-of-month invalid, it is adjusted to the last valid day in the month.

However, in my current project I need to be compatible with some existing PHP code like this:

$date = new \DateTime('2013-03-31');
echo $date->sub(new \DateInterval('P1M'))->format('Y-m-d');

The result here would be 2013-03-03, i.e. it is "rolling over" to the next month.

How can I achieve the same behaviour using Joda Time?

1 Answer 1

1

PHP seems to subtract the number of days it finds in the previous month. This should do it with Joda:

LocalDate date = new LocalDate(2013, 3, 31);
int numberOfDays = date.minusMonths(1).dayOfMonth().getMaximumValue();
System.out.println(date.minusDays(numberOfDays));
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.