Java Program To Add A Specified Number Of Days To A Given Date
Chapter:
Date and Time
Last Updated:
22-06-2023 14:11:02 UTC
Program:
/* ............... START ............... */
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class AddDaysToDate {
public static void main(String[] args) {
// Input date in string format
String inputDate = "2023-06-22";
// Number of days to add
int daysToAdd = 10;
// Create a DateTimeFormatter to parse the input date string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Parse the input date string into a LocalDate object
LocalDate date = LocalDate.parse(inputDate, formatter);
// Add the specified number of days to the date
LocalDate newDate = date.plusDays(daysToAdd);
// Format the new date back to a string
String result = newDate.format(formatter);
// Print the result
System.out.println("Original date: " + inputDate);
System.out.println("New date after adding " + daysToAdd + " days: " + result);
}
}
/* ............... END ............... */
Output
Original date: 2023-06-22
New date after adding 10 days: 2023-07-02
Notes:
-
In this program, you need to specify the input date as a string in the format "yyyy-MM-dd" and the number of days to add. The program uses the LocalDate class from the java.time package to perform the date manipulation. The DateTimeFormatter is used to parse and format the date string. The program then adds the specified number of days to the date using the plusDays() method and prints the result.
- When you run this program, it will output the original date and the new date after adding the specified number of days. For example, if you set the input date as "2023-06-22" and the number of days to add as 10, the output will be:
- Original date: 2023-06-22
- New date after adding 10 days: 2023-07-02
- Make sure to have Java 8 or above installed on your system to execute this program successfully.