Java Program to subtract hours from current time using Calendar.add() method

Java 8Object Oriented ProgrammingProgramming

Import the following package for Calendar class in Java.

import java.util.Calendar;

Firstly, create a Calendar object and display the current date and time.

Calendar calendar = Calendar.getInstance();
System.out.println("Current Date and Time = " + calendar.getTime());

Now, let us increment the hours using the calendar.add() method and Calendar.HOUR_OF_DAY constant. Set a negative value since you want to decrease the hours.

calendar.add(Calendar.HOUR_OF_DAY, +5);

Example

 Live Demo

import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      System.out.println("Current Date = " + calendar.getTime());
      // Incrementing hours by 5
      calendar.add(Calendar.HOUR_OF_DAY, +5);
      System.out.println("Updated Date = " + calendar.getTime());
   }
}

Output

Current Date = Thu Nov 22 16:13:04 UTC 2018
Updated Date = Thu Nov 22 21:13:04 UTC 2018
raja
Published on 06-Dec-2018 15:17:38
Advertisements