Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to add and subtract hour to current hours using Calendar class in Java ?.

Program to demonstrate addition and subtraction of hours to current hour of the day using Calendar class in Java


package com.hubberspot.example;

import java.util.Calendar;


public class TimeManipulation {

 public static void main(String[] args) {

  // Create a Calendar object
  Calendar calendar = Calendar.getInstance();

  // Get current day from calendar
  int day = calendar.get(Calendar.DATE);
  // Get current month from calendar
  int month = calendar.get(Calendar.MONTH) + 1;  
  // Get current year from calendar
  int year = calendar.get(Calendar.YEAR);

  System.out.print("Today's Date : ");
  // printing todays date in dd/mm/yy
  System.out.println(day+"/"+month+"/"+year);

  // Get current hour from calendar
  int hour = calendar.get(Calendar.HOUR_OF_DAY);
  // Get current minute from calendar
  int minutes = calendar.get(Calendar.MINUTE);
  // Get current second from calendar
  int seconds = calendar.get(Calendar.SECOND);

  System.out.print("Current Time : ");
  // printing current time in hh:mm:ss
  System.out.println(hour+":"+minutes+":"+seconds);

  // adding 6 hours to current hour of the day
  calendar.add(Calendar.HOUR_OF_DAY, 6);

  hour = calendar.get(Calendar.HOUR_OF_DAY);
  minutes = calendar.get(Calendar.MINUTE);
  seconds = calendar.get(Calendar.SECOND);

  System.out.print("Time after 6 hours : ");
  // printing time after 6 hours
  System.out.println(hour+":"+minutes+":"+seconds);

  // Calendar class automatically adjust date if 
  // on adding hours makes a date change
  day = calendar.get(Calendar.DATE);
  month = calendar.get(Calendar.MONTH) + 1;  
  year = calendar.get(Calendar.YEAR);

  System.out.print("Date after 6 hours : ");
  // printing date after 6 hours in dd/mm/yy
  System.out.println(day+"/"+month+"/"+year);

  // as our current hour is set to 6 hours plus from
  // the current hour , in order to subtract 6 
  // hours from current hour minus it with 12 
  calendar.add(Calendar.HOUR_OF_DAY, -12);

  hour = calendar.get(Calendar.HOUR_OF_DAY);
  minutes = calendar.get(Calendar.MINUTE);
  seconds = calendar.get(Calendar.SECOND);

  System.out.print("Time before 6 hours : ");
  // printing time after subtraction in hh:mm:ss
  System.out.println(hour+":"+minutes+":"+seconds);

 }

}




Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot