Question

I am trying to add 1 month on dates but the problem is when I have a date of Feb 28 then I add another month, I result to March 28. It should end on March 31. Same as when I started with a date of April 30, I should end in May 31 not May 30. I tried using plusMonths() of Jodatime and add() of java.util.date but still same problem.

Was it helpful?

Solution

Your expectation is simply wrong: it is supposed to move to the same day in the following month, if such exists. Anyway, how can the code know that you want Feb 28 to mean "the last day of February"? It legitimately means "the 28th day of February". Suppose you started with Jan 28, then added a month, then added one more, what result would you expect?

What you need can be achieved by working with the 1st of the following month and then moving one day back.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top