
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 Period to LocalDate in Java
In this program, we will learn to add a specific period to a date using Java's LocalDate class. By using Java's Period class, we can specify an amount of time (such as months and days) and then add this period to a LocalDate. The program demonstrates how to set a period and apply it to a given date to get a new, updated date.
Steps to add Period to LocalDate
Following are the steps to add Period to LocalDate ?
- Import LocalDate and Period from java.time package to work with dates and periods.
- Initialize the Period.ofMonths() and plusDays() to define a period with specific months and days. In this case, set 5 months and 15 days.
- Define a LocalDate using LocalDate.of() with a specific year, month, and day.
- We will apply the period to the date using the plus() method, which updates the date by the defined period.
- We will print the original date and the updated date to see the result.
Java program to add Period to LocalDate
Below is the Java program to add Period to LocalDate ?
import java.time.LocalDate; import java.time.Period; public class Demo { public static void main(String[] args) { Period p = Period.ofMonths(5).plusDays(15); LocalDate date = LocalDate.of(2019, 4, 10); System.out.println("Date = "+date); LocalDate res = date.plus(p); System.out.println("Updated date = "+res); } }
Output
Date = 2019-04-10 Updated date = 2019-09-25
Code explanation
In the above program, we begin by defining a period using Period.ofMonths(5).plusDays(15), which specifies a period of 5 months and 15 days. Next, we create an initial LocalDate set to 2019-04-10. By calling date.plus(p), where p is our defined period, we add this period to the original date. The updated date is then stored in res, and both the original and updated dates are printed. This allows us to verify that the period has been added correctly.