
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add 3 Months to the Calendar in Java
In this article, we will learn to add 3 months to the calendar. We will take the current date and add 3 months to it using Calendar class in Java. You'll see how to handle date manipulation and update the date accordingly.
Problem Statement
Write a program in Java to add 3 months to the calendar. Below is the demonstration of the same ?
Input
Current Date = Fri Nov 23 06:38:56 UTC 2018
Output
Updated Date = Sat Feb 23 06:38:56 UTC 2019
Different approaches
Below are the different approaches to add 3 months to the calendar ?
Using Calendar Class
Following are the steps to add 3 months to the calendar ?
- Import the Calendar class from the java.util package.
- Get the current date and time using Calendar.getInstance().
- Add 3 months to the current date using the add() method with Calendar.MONTH.
- Display the updated date.
Example
The following is an example of adding 3 months to the calendar ?
import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); System.out.println("Current Date = " + calendar.getTime()); // Add 3 months to the Calendar calendar.add(Calendar.MONTH, 3); System.out.println("Updated Date = " + calendar.getTime()); } }
Output
Current Date = Fri Nov 23 06:38:56 UTC 2018 Updated Date = Sat Feb 23 06:38:56 UTC 2019
Using Calendar and LocalDate class
Following are the steps to add 3 months to the calendar ?
- Import the LocalDate class and Period class from java.time.
- Get the current date using LocalDate.now().
- Add 3 months using plusMonths() method.
- Display the updated date.
Example
import java.time.LocalDate; public class Demo { public static void main(String[] args) { LocalDate currentDate = LocalDate.now(); System.out.println("Current Date = " + currentDate); // Add 3 months to the LocalDate LocalDate updatedDate = currentDate.plusMonths(3); System.out.println("Updated Date = " + updatedDate); } }
Output
Current Date = 2024-09-16
Updated Date = 2024-12-16
Advertisements