Java Calendar add()

By Arvind Rai, 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) 
The 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 is DAY_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 is MONTH.
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 is YEAR.
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 is HOUR.
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 

Reference

Class Calendar
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us