Skip to Content

Add or substract minutes to current time using Java Calendar

  1. /*
  2.   Add or substract minutes to current time using Java Calendar
  3.   This example shows how to add or substract minutes in current time  
  4.   using Java Calendar class.
  5. */
  6.  
  7. import java.util.Calendar;
  8.  
  9. public class AddMinutesToCurrentDate {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create Calendar instance
  14.     Calendar now = Calendar.getInstance();
  15.    
  16.     System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY)
  17.                       + ":"
  18.                       + now.get(Calendar.MINUTE)
  19.                       + ":"
  20.                       + now.get(Calendar.SECOND));
  21.                      
  22.     //add minutes to current date using Calendar.add method
  23.     now.add(Calendar.MINUTE,20);
  24.  
  25.     System.out.println("New time after adding 20 minutes : "
  26.                       + now.get(Calendar.HOUR_OF_DAY)
  27.                       + ":"
  28.                       + now.get(Calendar.MINUTE)
  29.                       + ":"
  30.                       + now.get(Calendar.SECOND));
  31.  
  32.     /*
  33.      * Java Calendar class automatically adjust the date or hour accordingly
  34. if adding minutes to the current time causes current hour or date to be changed.
  35.      */
  36.      
  37.  
  38.     //substract minutes from current date using Calendar.add method
  39.     now = Calendar.getInstance();
  40.     now.add(Calendar.MINUTE, -50);
  41.  
  42.     System.out.println("Time before 50 minutes : " + now.get(Calendar.HOUR_OF_DAY)
  43.                       + ":"
  44.                       + now.get(Calendar.MINUTE)
  45.                       + ":"
  46.                       + now.get(Calendar.SECOND));
  47.    
  48.   }
  49. }
  50.  
  51. /*
  52. Typical output would be
  53. Current time : 16:34:11
  54. New time after adding 20 minutes : 16:54:11
  55. Time before 25 minutes : 15:44:11
  56. */