Странное поведение от java.util.calendar в февралеJAVA

Программисты JAVA общаются здесь
Anonymous
Странное поведение от java.util.calendar в феврале

Сообщение Anonymous »

Я столкнулся со странным поведением от java.util.calendar: < /p>

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;
}
}
< /code>

Я хочу знать, почему именно это происходит? < /p>

Подробнее здесь: https://stackoverflow.com/questions/146 ... n-february

Вернуться в «JAVA»