Introducing Radical.sh

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

Adding or Subtracting Minutes to Current Time in Java

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