1.

How can we subtract hours from current time in Java?

Answer»

To subtract hours, you need to USE the HOUR_OF_DAY constant. Within that, INCLUDE the number with the negative sign. This WOULD be the hours you want to REDUCE. All this is done under the Calendar add() method.

The following is an example:

import java.util.Calendar; public class Example {  public static void main(String[] args) {    Calendar c = Calendar.getInstance();    System.out.println("Date : " + c.getTime());    // 2 hours subtracted    c.add(Calendar.HOUR_OF_DAY, -2);    System.out.println("After subtracting 2 hrs : " + c.getTime());  } }

Here is the output:

Date : Sun Dec 16 16:28:53 UTC 2018 After subtracting 2 hrs : Sun Dec 16 14:28:53 UTC 2018


Discussion

No Comment Found