Introducing Radical.sh

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

Adding or Subtracting Seconds to Current Time in Java

  1. import java.util.Calendar;
  2. public class Seconds {
  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 seconds to current date using Calendar.add method
  12. now.add(Calendar.SECOND,100);
  13. System.out.println("New time after adding 100 seconds : "
  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,hour or minutesaccordingly
  21. * if adding seconds to the current time causes current minute,
  22. * hour or date to be changed.
  23. */
  24. //substract seconds from current time using Calendar.add method
  25. now = Calendar.getInstance();
  26. now.add(Calendar.SECOND, -50);
  27. System.out.println("Time before 50 minutes : " + now.get(Calendar.HOUR_OF_DAY)
  28. + ":"
  29. + now.get(Calendar.MINUTE)
  30. + ":"
  31. + now.get(Calendar.SECOND));
  32. }