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 minutes to current minutes using Calendar class in Java ?.

Program to demonstrate addition and subtraction of minutes to current minute of the day using Calendar class in Java

package com.hubberspot.example;

import java.util.Calendar;


public class MinuteManipulation {

 public static void main(String[] args) {

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

  // 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 40 minutes to current hour of the day
  calendar.add(Calendar.MINUTE, 40);

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

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

  calendar = Calendar.getInstance();

  calendar.add(Calendar.MINUTE, -40);

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

  System.out.print("Time before 40 minutes : ");
  // printing time before 40 minutes
  System.out.println(hour+":"+minutes+":"+seconds);



 }

}




Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot