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);
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With