gpt4 book ai didi

添加月份时的 Java 日历/日期问题

转载 作者:行者123 更新时间:2023-12-01 07:31:38 25 4
gpt4 key购买 nike

如果我们在当前日期(2013 年 5 月 31 日星期五 18:33:00 IST 2013)中添加 1 个月,则得出:

2013 年 6 月 30 日星期日 18:33:00 IST

如果我们减去 1 个月,结果是:

5 月 30 日星期四 18:33:00 IST 2013

这是一个错误还是有人可以提供推理?

请找到相同的代码:

Calendar c1 = Calendar.getInstance()
System.out.println(c1.getTime());
c1.add(Calendar.MONTH, 1);
System.out.println(c1.getTime());
c1.add(Calendar.MONTH, -1);
System.out.println(c1.getTime());

输出

Fri May 31 18:33:00 IST 2013
Sun Jun 30 18:33:00 IST 2013
Thu May 30 18:33:00 IST 2013

最佳答案

更改月份中的某一天是预期的行为,此处记录为“添加规则 2”:http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html

add(f, delta) adds delta to field f. This is equivalent to calling set(f, get(f) + delta) with two adjustments:

Add rule 1. The value of field f after the call minus the value of field f before the call is delta, modulo any overflow that has occurred in field f. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.

Add rule 2. If a smaller field is expected to be invariant, but it is impossible for it to be equal to its prior value because of changes in its minimum or maximum after field f is changed or other constraints, such as time zone offset changes, then its value is adjusted to be as close as possible to its expected value. A smaller field represents a smaller unit of time. HOUR is a smaller field than DAY_OF_MONTH. No adjustment is made to smaller fields that are not expected to be invariant. The calendar system determines what fields are expected to be invariant.

有了这些规则,如果您添加 1 个月,然后添加 -1 个月,则无法保留月份中的日期。

关于添加月份时的 Java 日历/日期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16941220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com