开发者

Joda DateTime not giving the expected results

开发者 https://www.devze.com 2023-03-08 04:58 出处:网络
Given a DateTime object at 31-March-2011 and this code: DateTime temp1 = new DateTime(2011, 3, 31, 12, 0, 0, 0);

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-30开发者_如何学CT12: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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号