Java Calendar add()
May 14, 2022
On this page we will learn using Calendar.add
method. The java.util.Calendar
class provides methods for converting between a specific instant in time and a set of calendar fields. The Calendar
fields are DAY_OF_MONTH, WEEK_OF_MONTH, DAY_OF_YEAR etc.
Here on this page we will discuss calendar
add()
method.
void add(int field, int amount)
add()
method adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.
field: The calendar field.
amount: The amount of date or time to be added to the field.
Add and Subtract Days
Here calendar field isDAY_OF_MONTH
.
Calendar c = Calendar.getInstance(); System.out.println(c.getTime()); // Sat May 14 11:40:27 IST 2022 c.add(Calendar.DAY_OF_MONTH, 5); System.out.println(c.getTime()); // Thu May 19 11:40:27 IST 2022 c.add(Calendar.DAY_OF_MONTH, -3); System.out.println(c.getTime()); // Mon May 16 11:40:27 IST 2022
Add and Subtract Month
Here calendar field isMONTH
.
Calendar c = Calendar.getInstance(); System.out.println(c.getTime()); // Sat May 14 11:47:23 IST 2022 c.add(Calendar.MONTH, 3); System.out.println(c.getTime()); // Sun Aug 14 11:47:23 IST 2022 c.add(Calendar.MONTH, -2); System.out.println(c.getTime()); // Tue Jun 14 11:47:23 IST 2022
Add and Subtract Year
Here calendar field isYEAR
.
Calendar c = Calendar.getInstance(); System.out.println(c.getTime()); // Sat May 14 11:53:15 IST 2022 c.add(Calendar.YEAR, 4); System.out.println(c.getTime()); // Thu May 14 11:53:15 IST 2026 c.add(Calendar.YEAR, -3); System.out.println(c.getTime()); // Sun May 14 11:53:15 IST 2023
Add and Subtract Hour
Here calendar field isHOUR
.
Calendar c = Calendar.getInstance(); System.out.println(c.getTime()); // Sat May 14 11:55:20 IST 2022 c.add(Calendar.HOUR, 4); System.out.println(c.getTime()); // Sat May 14 15:55:20 IST 2022 c.add(Calendar.HOUR, -2); System.out.println(c.getTime()); // Sat May 14 13:55:20 IST 2022