Modify Date and Time from GregorianCalendar in Java

Java 8Object Oriented ProgrammingProgramming

For GregorianCalendar class, import the following package.

import java.util.GregorianCalendar;

Firstly, let us display the current date and time.

GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
System.out.println("Current date: " + cal.getTime());

Now, modify the date. Here we are adding two days to the month using the add() method.

cal.add((GregorianCalendar.MONTH), 2);

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());
      cal.add((GregorianCalendar.MONTH), 2);
      System.out.println("Modified date: " + cal.getTime());
   }
}

Output

Current date: Mon Nov 19 17:52:55 UTC 2018
Modified date: Sat Jan 19 17:52:55 UTC
raja
Published on 17-Dec-2018 12:41:05
Advertisements