Tuesday 20 November 2012

Add or substract hours to current time using Java Calendar

Leave a Comment

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

0 comments:

Post a Comment