How to Add Or Subtract Hours in Java


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

Source Code

package com.beginner.examples;

import java.util.Calendar;

public class ASHoursExample {

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

Output:

6
7
6

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments