Calendar.add()

Date

Calendar.add(field,int amount) add the input amount to the given field.

field : Required , field on which the amount will be added.
amount : Required , amount to be added to field.

Examples with output
Adding 4 days
Calendar my_cal = Calendar.getInstance();// created calendar 
//Year, Month, Date, Hour, Minute, Second
my_cal.set(2020, 5, 25,22,59,45);
my_cal.add(Calendar.DATE, 4);

System.out.println(my_cal.get(Calendar.YEAR)); //  2020
System.out.println(my_cal.get(Calendar.MONTH)); // 5
System.out.println(my_cal.get(Calendar.WEEK_OF_MONTH)); // 4
System.out.println(my_cal.get(Calendar.DATE)); // 29
We will add to other fields
package my_proj;
import java.util.Calendar; 
public class my_first {
public static void main(String[] args) {
    
Calendar my_cal = Calendar.getInstance();// created calendar 
//Year, Month, Date, Hour, Minute, Second
my_cal.set(2020, 5, 25,22,59,45);
 
my_cal.add(Calendar.YEAR, 2); // adding 2 years
my_cal.add(Calendar.MONTH,3); // adding 3 months
my_cal.add(Calendar.DATE, 4); // adding 4 days
my_cal.add(Calendar.HOUR, 5); // adding 5 Hours
my_cal.add(Calendar.MINUTE,10); // adding 10 Minutes
my_cal.add(Calendar.SECOND,10); // adding 10 Seconds
my_cal.add(Calendar.MILLISECOND,100); // adding 10 Seconds

System.out.println(my_cal.get(Calendar.YEAR)); //  2022
System.out.println(my_cal.get(Calendar.MONTH)); // 8
System.out.println(my_cal.get(Calendar.DATE)); // 29
System.out.println(my_cal.get(Calendar.HOUR)); // 4
System.out.println(my_cal.get(Calendar.MINUTE)); // 9
System.out.println(my_cal.get(Calendar.SECOND)); // 55
System.out.println(my_cal.get(Calendar.MILLISECOND)); // 379
}
}
Note that we have added 10 minutes to 59 minutes , so the hour count is also increased by 1 ( from 3 to 4 ) .

Date & time tutorials


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer