Subtract Hours from Current Time Using Calendar Add Method in Java



In this article, we use the Calendar class in Java to work with dates and times. First, it retrieves the current date and time and displays it. Then, the program increments the current time by 5 hours using the add() method and displays the updated date and time. This is a simple example of modifying and handling date-time values programmatically. Subtracting hours from current time using Calendar.add() method.

Calendar class

The Java Calendar class is found in the java.util package. It is an abstract class that provides methods for converting a specific moment in time into various calendar fields such as YEAR, MONTH, DAY_OF_MONTH, and HOUR. It also allows for manipulating these fields, such as calculating the date for the next week.

We will be using:

getInstance() Method

The getInstance() method creates a Calendar object representing the current date and time based on the system's default time zone and locale.

Calendar calendar = Calendar.getInstance();

In the above line, it initializes the Calendar instance to retrieve the current date and time.

getTime() Method

The getTime() method converts the Calendar object to a Date object and returns the current date and time in a readable format.

System.out.println("Current Date = " + calendar.getTime());
System.out.println("Updated Date = " + calendar.getTime());

Calendar.add() Method

The Java Calendar add() method adjusts the specified calendar field by a given amount of time, either adding or subtracting, according to the rules of the calendar.

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

Subtracting hours from current time using Calendar.add() method

Following are the steps to subtract hours from current time using Calendar.add() method ?

  • Create a calendar object we will use Calendar.getInstance() to obtain the current date and time.
  • Display the current date and time call calendar.getTime() to convert the Calendar object to a Date object.
  • Add 5 hours to the current time we will use the calendar.add(Calendar.HOUR_OF_DAY, +5) to increment the current time by 5 hours.
  • Display the updated date and time by calling the calendar.getTime() to display the updated date and time after the 5-hour increment.

Example

Below is the Java program to subtract hours from current time using Calendar.add() method ?

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
Updated on: 2024-11-20T22:39:59+05:30

701 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements