Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Adding and Subtracting Hours to the current time in Java

  1. import java.util.Calendar;
  2. public class HourstoCurrDate {
  3. public static void main(String[] args) {
  4. //create Calendar instance
  5. Calendar now = Calendar.getInstance();
  6. System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1)
  7. + "-"
  8. + now.get(Calendar.DATE)
  9. + "-"
  10. + now.get(Calendar.YEAR));
  11. System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY)
  12. + ":"
  13. + now.get(Calendar.MINUTE)
  14. + ":"
  15. + now.get(Calendar.SECOND));
  16. //add hours to current date using Calendar.add method
  17. now.add(Calendar.HOUR,10);
  18. System.out.println("New time after adding 10 hours : "
  19. + now.get(Calendar.HOUR_OF_DAY)
  20. + ":"
  21. + now.get(Calendar.MINUTE)
  22. + ":"
  23. + now.get(Calendar.SECOND));
  24. /*
  25. * Java Calendar class automatically adjust the date accordingly if adding
  26. * hours to the current time causes current date to be changed.
  27. */
  28. System.out.println("New date after adding 10 hours : "
  29. + (now.get(Calendar.MONTH) + 1)
  30. + "-"
  31. + now.get(Calendar.DATE)
  32. + "-"
  33. + now.get(Calendar.YEAR));
  34. //substract hours from current date using Calendar.add method
  35. now = Calendar.getInstance();
  36. now.add(Calendar.HOUR, -3);
  37. System.out.println("Time before 3 hours : " + now.get(Calendar.HOUR_OF_DAY)
  38. + ":"
  39. + now.get(Calendar.MINUTE)
  40. + ":"
  41. + now.get(Calendar.SECOND));
  42. }
  43. }