Sunday, 22 July 2012

How to Add or Subtract time using Calendar in Java

The java.util.Calendar allows us to do a date arithmetic function such as add or subtract a unit of time to the specified date field.


The method that done this process is the Calendar.add(int field, int amount). Where the value of the field can be Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND. So this mean if you want to subtract in hours, minutes or seconds use Calendar.HOUR, Calendar.MINUTE or Calendar.SECOND respectively.



The complete source code is given below:




import java.util.Calendar;
public class CalendarAddExample {
	public static void main(String[] args) {
		Calendar cal = Calendar.getInstance();

		System.out.println("Today : " + cal.getTime());

		// Subtract 2 hours from the calendar
		cal.add(Calendar.HOUR, -2);
		System.out.println("2 hours ago: " + cal.getTime());

		// Add 10 minutes to the calendar
		cal.add(Calendar.MINUTE, 10);
		System.out.println("10 minutes later: " + cal.getTime());

		// Subtract 15 seconds from the calendar
		cal.add(Calendar.SECOND, -15);
		System.out.println("15 seconds ago: " + cal.getTime());
	}
}

The output is


Today : Mon Jul 23 09:51:53 IST 2012
2 hours ago: Mon Jul 23 07:51:53 IST 2012
10 minutes later: Mon Jul 23 08:01:53 IST 2012
15 seconds ago: Mon Jul 23 08:01:38 IST 2012




The links that may help you:


No comments:

Post a Comment