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); 

3 Answers 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); 
Sign up to request clarification or add additional context in comments.

2 Comments

isn't Calendar.HOUR a unit of time of 12hours (0-11). So it's (12 * 11) + 8 = 140, rolling back 8 hrs? Or did OP mean HOUR_OF_DAY vs HOUR
Good catch. By HOUR its a 8 hour rollback and by HOUR_OF_DAY it would be a 20 hour rollback.
2

If you store the date in a Calendar object called 'rightNow' you can use the following code:

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

Where:

numberOfHours: Is the amount of hours you want to subtract.

Comments

0

Roll depends on implementation, see http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#roll%28int,%20int%29

Probably your default implementation rolls maximum one day. Rather to use GregorianCalendar or Joda http://joda-time.sourceforge.net/.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.