Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Java program to display previous month from GregorianCalendar
The GregorianCalendar class in Java allows us to manipulate dates and times easily. In this example, we will create a GregorianCalendar object and use it to display the current date and the date of the previous month.
Problem Statement
Write a Java program and create a GregorianCalendar object, display the current date, and then modify this date to show the date of the previous month.
Output
Current date: Mon Nov 19 18:07:03 UTC 2018
Input
Modified date (Previous Month): Fri Oct 19 18:07:03 UTC 2018
Steps to display previous month from GregorianCalendar
Below are the steps to display previous month from GregorianCalendar ?
- Import the necessary packages.
- Create a GregorianCalendar object using GregorianCalendar.getInstance().
- Display the current date.
- Use the add() method with the MONTH field and a value of -1 to subtract one month from the current date.
- Display the modified date.
Java program to display previous month from GregorianCalendar
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());
// past month
cal.add((GregorianCalendar.MONTH), -1);
System.out.println("Modified date (Previous Month): " + cal.getTime());
}
}
Output
Current date: Mon Nov 19 18:07:03 UTC 2018 Modified date (Previous Month): Fri Oct 19 18:07:03 UTC 2018
Code Explanation
Initially, we will import the GregorianCalender class and Calender class from java.util package.
import java.util.GregorianCalendar;
We create a GregorianCalendar object named cal using GregorianCalendar.getInstance(), which initializes it to the current date and time.
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
Now, use the following field and add() method with a negative one -1 to display the previous month.
cal.add((GregorianCalendar.MONTH), -1)
Finally, we print the modified date to show the date of the previous month.
