4

Based on my understanding of the roll() method, I expected the below code to subtract 140 hours from the current time. But it seems to be subtracting 20 hours. Is this not the proper way to do this?

Calendar rightNow = Calendar.getInstance();
rightNow.roll(Calendar.HOUR, -140);
4

3 回答 3

9

As per the java docs, the roll method does not change larger fields and it will roll the hour value in the range between 0 and 23.

So in your case, considering HOUR_OF_DAY, 140 is actually considered as (24 * 5) + 20 = 140. Now since it does not change larger fields the "hour" is rolled back by 24 hours 5 times which gets it back to the same time and then it rolls it back by 20 hours.

To achieve a "real" 140 hours roll back you can do it like -

    Calendar rightNow = Calendar.getInstance();
    rightNow.add(Calendar.HOUR, -140);
于 2013-06-26T19:41:43.720 回答
2

如果您将日期存储在名为“rightNow”的日历对象中,则可以使用以下代码:

Calendar rightNow = Calendar.getInstance();
rightNow.add(Calendar.HOUR_OF_DAY, -numberOfHours);

在哪里:

numberOfHours:是您要减去的小时数。

于 2013-06-26T21:18:02.517 回答
0

滚动取决于实现,请参阅http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#roll%28int,%20int%29

可能您的默认实现最多滚动一天。而是使用 GregorianCalendar 或 Joda http://joda-time.sourceforge.net/

于 2013-06-26T19:57:55.190 回答