How to Add Or Subtract Seconds in Java


Here we will write an example to add or substract seconds in current time with java Calendar class.

Source Code

package com.beginner.examples;

import java.util.Calendar;

public class ASSecondsExample {

    public static void main(String[] args){
    	//get calendar
    	Calendar now = Calendar.getInstance();
    	System.out.println(now.get(Calendar.SECOND));
		//seconds add 1
    	now.add(Calendar.SECOND, 1);
		System.out.println(now.get(Calendar.SECOND));
		//seconds subtract 1
		now.add(Calendar.SECOND, -1);
		System.out.println(now.get(Calendar.SECOND));
	}
}

Output:

34
35
34

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments