Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract hours from a calendar instance

Tags:

java

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);
like image 589
Webnet Avatar asked Dec 20 '22 03:12

Webnet


2 Answers

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);
like image 192
JHS Avatar answered Jan 03 '23 23:01

JHS


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.

like image 20
Ricardo Avatar answered Jan 03 '23 21:01

Ricardo