gpt4 book ai didi

java - 二月 java.util.Calendar 的奇怪行为

转载 作者:搜寻专家 更新时间:2023-10-31 08:15:21 24 4
gpt4 key购买 nike

我遇到了来自 java.util.Calendar 的奇怪行为:

import static org.junit.Assert.*;
import org.junit.Test;

import java.util.Calendar;

public class Tester1 {
@Test
public void test_monthOfDate() {
assertEquals(1, monthOfDate(2013, 1, 30)); // OK
assertEquals(1, monthOfDate(2013, 1, 31)); // OK

// Start of February
assertEquals(2, monthOfDate(2013, 2, 1)); // FAIL
assertEquals(2, monthOfDate(2013, 2, 28)); // FAIL
// to the end of it

// and after that it is okay also
assertEquals(3, monthOfDate(2013, 3, 1)); // OK
}

public int monthOfDate(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);

// just a simple get! but seems it is very important
cal.get(Calendar.MONTH);
//

cal.set(Calendar.DAY_OF_MONTH, day);

return cal.get(Calendar.MONTH) + 1;
}
}

我想知道为什么会这样?

最佳答案

问题是您从 2013 年 1 月 30 日开始使用日历。

然后您将年份设置为 2013 - 这不是问题。

然后您将月份设置为 1(即二月)。你希望这里发生什么?实际发生的是它会记住需要将月份设置为 1,但不会重新计算实际时间值。不过,根据 documentation,时间值在您调用 get 时重新计算。 (强调我的):

set(f, value) changes calendar field f to value. In addition, it sets an internal member variable to indicate that calendar field f has been changed. Although calendar field f is changed immediately, the calendar's time value in milliseconds is not recomputed until the next call to get(), getTime(), getTimeInMillis(), add(), or roll() is made. Thus, multiple calls to set() do not trigger multiple, unnecessary computations. As a result of changing a calendar field using set(), other calendar fields may also change, depending on the calendar field, the calendar field value, and the calendar system. In addition, get(f) will not necessarily return value set by the call to the set method after the calendar fields have been recomputed. The specifics are determined by the concrete calendar class.

当您尝试将“1 月 30 日”更改为“2 月 30 日”并强制进行计算时,实际上发生的是您在我的框中结束于 3 月 2 日 - 但它可能与您的不同实现。

最好的修复是:

关于java - 二月 java.util.Calendar 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14605360/

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