Menu
Topics Index
...
`

Gregorian Calendar Methods - Java Example Program


Gregorian Calendar Methods
import java.util.*;

class GregorianCalendarMethodsTest1
{
    public static void main(String arg[])
    {
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        System.out.println("The current date : " + gc.getTime());
        
        gc.add(Calendar.MONTH, 3); // Adds 3 months // LINE A
        System.out.println("Adds 3 months to present year : " + gc.getTime());
        
        GregorianCalendar gc1 = (GregorianCalendar) gc.clone(); // Cloning method
        System.out.println("Clone date : " + gc1.getTime());
        
        if (gc.equals(gc1)) { // Equals method
            System.out.println("Both calendars are same");
        }
        
        System.out.println("The 2016 is Leap Year : " + gc.isLeapYear(2016)); // Leap year
        
        gc.roll(Calendar.DAY_OF_MONTH, true); // Rolls a single day
        System.out.println("Adds a single day : " + gc.getTime());
        
        gc.roll(Calendar.DAY_OF_MONTH, 5); // Rolls 5 days
        System.out.println("Adds five days : " + gc.getTime());
        
        gc.set(Calendar.MONTH, 11); // Sets month as December    
    }
}
OUTPUT

The current date : Sun Jan 19 12:58:07 IST 2014
Adds 3 months to present year : Sat Apr 19 12:58:07 IST 2014
Clone date : Sat Apr 19 12:58:07 IST 2014
Both calendars are same
The 2016 is Leap Year : true
Adds a single day : Sun Apr 20 12:58:07 IST 2014
Adds five days : Fri Apr 25 12:58:07 IST 2014

DESCRIPTION

In this program, The getInstance method takes the current date in gc object. The add, clone, equals, isLeapYear, and  roll methods are used.

THINGS TO TRY
  • At LINE A, add method, replace -2 in place of 3 and see the output difference.
  • In isLeapYear method replace 2015 in place of 2016 and see the output difference.
  • In roll method replace false in place of true and see the output difference.
  • In roll method replace Calendar.MONTH in place of Calendar.DAY_OF_MONTH and see the output difference.

© meritcampus 2019

All Rights Reserved.

Open In App