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 isCalendar.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 isCalendar.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.
delete mistake.