Home » Java programming language

Java GregorianCalendar add() Method with Example

GregorianCalendar Class add() method: Here, we are going to learn about the add() method of GregorianCalendar Class with its syntax and example.
Submitted by Preeti Jain, on February 15, 2020

GregorianCalendar Class add() method

  • add() method is available in java.util package.
  • add() method is used to add the given quantity to the specified GregorianCalendar field (fi).
  • add() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • add() method may throw an exception at the time of adding the given quantity to the given field (fi).
    IllegalArgumentException: This exception may throw when the given field (fi) is not in a range.

Syntax:

    public void add(int fi , int quantity);

Parameter(s):

  • int fi – represents the GregorianCalendar field.
  • int quantity – represents the quantity of time to be added to the given calendar field.

Return value:

The return type of this method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void add(int fi , int quantity) method of 
// GregorianCalendar 

import java.util.*;

public class AddOfGregorianCalendar {
    public static void main(String[] args) {
        // Instantiating a GregorianCalendar object
        GregorianCalendar g_ca = (GregorianCalendar) GregorianCalendar.getInstance();

        // Display current GregorianCalendar
        System.out.println("g_ca.getTime() : " + g_ca.getTime());

        // By using add() method is to substract 3 years
        // to the current GregorianCalendar
        g_ca.add(GregorianCalendar.YEAR, -3);

        // Display Update GregorianCalendar
        System.out.println("g_ca.add(GregorianCalendar.YEAR, -3): " + g_ca.getTime());

        // By using add() method is to add 5 months
        // to the current GregorianCalendar
        g_ca.add(GregorianCalendar.MONTH, 5);

        // Display Update Calendar
        System.out.println("g_ca.add(GregorianCalendar.MONTH, 3): " + g_ca.getTime());

        // By using add() method is to substract 2 days
        // to the current GregorianCalendar
        g_ca.add(GregorianCalendar.DATE, -2);

        // Display Update GregorianCalendar
        System.out.println("g_ca.add(GregorianCalendar.DATE, -2): " + g_ca.getTime());
    }
}

Output

g_ca.getTime() : Sat Feb 15 06:51:12 GMT 2020
g_ca.add(GregorianCalendar.YEAR, -3): Wed Feb 15 06:51:12 GMT 2017
g_ca.add(GregorianCalendar.MONTH, 3): Sat Jul 15 06:51:12 GMT 2017
g_ca.add(GregorianCalendar.DATE, -2): Thu Jul 13 06:51:12 GMT 2017


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.