Calendar

Add/Subtract Hours from Date with Calendar

In this example we shall show you how to add and substract Hours from a Date with the Calendar class. Using this abstract class we can convert between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR. To add and substract Hours from Date with the Calendar one should perform the following steps:

  • Create a new Calendar object, using getInstance() API method of Calendar, that gets a calendar using the default time zone and locale.
  • Use add(int field, int amount) API method of Calendar to add an int amount of time to the given calendar field, that is Calendar.HOUR.
  • Use add(int field, int amount) API method of Calendar again, this time to subtract an int amount of time to the given calendar field, that is Calendar.HOUR.
  • In order to get the time that the calendar object represents every time that it is changed we can use the getTime() method of Calendar,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.util.Calendar;

public class AddSubtractDateHours {

	public static void main(String[] args) {

		int hoursToAdd = 4;
		int hoursToSubtract = 10;

		Calendar c = Calendar.getInstance();

		System.out.println("Current date : " + c.getTime());

		// add months to current date
		c.add(Calendar.HOUR, hoursToAdd);

		System.out.println("Current date : " + c.getTime());

		c = Calendar.getInstance();

		c.add(Calendar.HOUR, -hoursToSubtract);

		System.out.println("Current date : " + c.getTime());

	}

}

Output:

Current date : Wed Oct 19 22:42:21 EEST 2011 Current date : Thu Oct 20 02:42:21 EEST 2011 Current date : Wed Oct 19 12:42:21 EEST 2011

 
This was an example of how to add and substract Hours from Date with the Calendar in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Hélène
Hélène
6 years ago

delete mistake.

Back to top button