Reputation: 669
Given a DateTime
object at 31-March-2011 and this code:
DateTime temp1 = new DateTime(2011, 3, 31, 12, 0, 0, 0);
DateTime temp2 = temp1.plusMonths(1);
DateTime temp3 = temp2.plusMonths(1);
after the execution
temp1 = 2011-03-31T12:00:00.000+02:00
temp2 = 2011-04-30T12:00:00.000+02:00
temp3 = 2011-05-30T12:00:00.000+02:00
temp3 is wrong here.
Is that above correct. Am I doing a mistake?
Upvotes: 0
Views: 140
Reputation: 1499770
No, there's no mistake here. You're adding one month twice, which means the second time you'll get the result of adding a month to the possibly truncated result of adding the first month.
April only has 30 days, which is why you're getting April 30th for temp2
- and adding one month to April 30th gets you to May 30th.
If you want May 31st, use:
DateTime temp3 = temp1.plusMonths(2);
Basically, date and time arithmetic gives "odd" results if you try to think of it in terms of associativity etc.
Upvotes: 5