我在一些java代码中发现了一条注释,该代码指出getTime()需要调用它来更新Calendar对象.这是真的?我找不到任何说这是必要的东西.
这是代码:
Calendar cal = new GregorianCalendar();
cal.setFirstDayOfWeek(Calendar.SUNDAY);
cal.set(2009, 9 - 1, 10, 2, 30);
// Get Time needs to be called to update the Calendar object
cal.getTime();
Run Code Online (Sandbox Code Playgroud)
duk*_*ash 10
cal.getTime()确实需要调用它来重新计算其内部结构.这是一个非常奇怪的API行为,但Calendar javadocs明确说明了这一点:
获取和设置日历字段值
可以通过调用set方法来设置日历字段值.在需要计算其时间值(距Epoch的毫秒数)或日历字段的值之前,不会解释日历中设置的任何字段值.调用get,getTimeInMillis,getTime,add和roll涉及这样的计算.
...
野外操纵
可以使用三种方法更改日历字段:set(),add()和roll().set(f,value)将日历字段f更改为值.此外,它设置内部成员变量以指示日历字段f已更改.虽然日历字段f立即更改,但在下一次调用get(),getTime(),getTimeInMillis(),add()或roll()之前,不会重新计算日历的时间值(以毫秒为单位).因此,对set()的多次调用不会触发多次不必要的计算.作为使用set()更改日历字段的结果,其他日历字段也可能会更改,具体取决于日历字段,日历字段值和日历系统.此外,在重新计算日历字段后,get(f)不一定返回通过调用set方法设置的值.
行为是意外的,并不总是发生,但以下单元测试应该举例说明这种行为并始终发生.
/**
* Fails the assertion due to missing getTime()
* @throws ParseException
*/
public class DateTest {
@Test
public void testNoGetTime() throws ParseException {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date testDate = df.parse("04/15/2013");
Calendar testCal = Calendar.getInstance();
testCal.setTime(testDate);
Date expectedDate = df.parse("04/04/2013");
Date actualDate = null;
testCal.set(Calendar.DAY_OF_MONTH, testCal.getMinimum(Calendar.DAY_OF_MONTH));
//testCal.getTime();
testCal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
testCal.add(Calendar.DAY_OF_MONTH, -1);
actualDate = testCal.getTime();
assertEquals("Dates should be equal", expectedDate.toString(), actualDate.toString());
}
@Test
public void testWithGetTime() throws ParseException {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date testDate = df.parse("04/15/2013");
Calendar testCal = Calendar.getInstance();
testCal.setTime(testDate);
Date expectedDate = df.parse("04/04/2013");
Date actualDate = null;
testCal.set(Calendar.DAY_OF_MONTH, testCal.getMinimum(Calendar.DAY_OF_MONTH));
testCal.getTime();
testCal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
testCal.add(Calendar.DAY_OF_MONTH, -1);
actualDate = testCal.getTime();
assertEquals("Dates should be equal", expectedDate.toString(), actualDate.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4694 次 |
| 最近记录: |