Add or subtract seconds to current time using Calendar - Java Date Time

Java examples for Date Time:Calendar

Description

Add or subtract seconds to current time using Calendar

Demo Code


import java.util.Calendar;
 
public class Main {
 
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY)
                      + ":"
                      + now.get(Calendar.MINUTE)
                      + ":"
                      + now.get(Calendar.SECOND));
                     //from www .  j  ava  2  s .co  m
    now.add(Calendar.SECOND,100);
 
    System.out.println("New time after adding 100 seconds : "
                      + now.get(Calendar.HOUR_OF_DAY)
                      + ":"
                      + now.get(Calendar.MINUTE)
                      + ":"
                      + now.get(Calendar.SECOND));
 
    //subtract seconds from current time using Calendar.add method
    now = Calendar.getInstance();
    now.add(Calendar.SECOND, -50);
 
    System.out.println("Time before 50 minutes : " + now.get(Calendar.HOUR_OF_DAY)
                      + ":"
                      + now.get(Calendar.MINUTE)
                      + ":"
                      + now.get(Calendar.SECOND));
  }
}
 

Result


Related Tutorials