Java Program to display previous year from GregorianCalendar

Java 8Object Oriented ProgrammingProgramming

For GregorianCalendar class, import the following package.

import java.util.GregorianCalendar;

Create an object.

GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();

Now, use the following field and add() method with a negative one (-1) to display the previous year.

cal.add((GregorianCalendar.YEAR), -1)

Example

 Live Demo

import java.util.Calendar;
import java.util.GregorianCalendar;
public class Demo {
   public static void main(String[] a) {
      GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
      System.out.println("Current date: " + cal.getTime());
      // previous year
      cal.add((GregorianCalendar.YEAR), -1);
      System.out.println("Modified date: " + cal.getTime());
   }
}

Output

Current date: Mon Nov 19 18:05:49 UTC 2018
Modified date: Sun Nov 19 18:05:49 UTC 2017
raja
Published on 17-Dec-2018 17:13:28
Advertisements