Modify Date and Time from GregorianCalendar in Java


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 27-Jun-2020

625 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements