Skip to main content

APIzation: Replication Package

[Q#17329006][A#17329022] How to subtract hours from a calendar instance

https://stackoverflow.com/q/17329006

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?

Answer

https://stackoverflow.com/a/17329022

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 -

APIzation

Calendar rightNow = Calendar.getInstance();
    rightNow.add(Calendar.HOUR, -140);
package com.stackoverflow.api;

import java.util.Calendar;

public class Human17329022 {

  public static void subtractHours(Calendar rightNow) {
    rightNow.add(Calendar.HOUR, -140);
  }
}

package com.stackoverflow.api;

import java.util.Calendar;

/**
 * How to subtract hours from a calendar instance
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/17329022">https://stackoverflow.com/a/17329022</a>
 */
public class APIzator17329022 {

  public static void subtractHour() throws Exception {
    Calendar rightNow = Calendar.getInstance();
    rightNow.add(Calendar.HOUR, -140);
  }
}