Java Add Months To Date
Chapter:
Date and Time
Last Updated:
14-05-2023 05:44:50 UTC
Program:
/* ............... START ............... */
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateExample {
public static void main(String[] args) {
// Get the current date
LocalDate currentDate = LocalDate.now();
System.out.println("Current date: " + formatDate(currentDate));
// Add 3 months to the current date
LocalDate futureDate = currentDate.plusMonths(3);
System.out.println("Date after adding 3 months: " + formatDate(futureDate));
}
private static String formatDate(LocalDate date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return date.format(formatter);
}
}
/* ............... END ............... */
Output
Current date: 2023-05-14
Date after adding 3 months: 2023-08-14
Notes:
-
In this example, we start by obtaining the current date using LocalDate.now(). We then add 3 months to the current date using the plusMonths() method. Finally, we format the dates using the DateTimeFormatter to display them in the desired format ("yyyy-MM-dd").
- When you run this code, it will output the current date and the date after adding 3 months.
- The formatDate() method takes a LocalDate object and formats it into a string representation using the specified date format ("yyyy-MM-dd"). This method uses the DateTimeFormatter class to format the date.