Java program to add two dates
Here's a Java program that adds two dates:
import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class DateAddition { public static void main(String[] args) { // Create two date objects LocalDate date1 = LocalDate.parse("2022-02-15", DateTimeFormatter.ISO_DATE); LocalDate date2 = LocalDate.parse("2023-02-16", DateTimeFormatter.ISO_DATE); // Add the two dates LocalDate result = date1.plusDays(date2.getDayOfMonth()).plusMonths(date2.getMonthValue()).plusYears(date2.getYear()); // Print the result System.out.println("Result: " + result.format(DateTimeFormatter.ISO_DATE)); } }Sourcww:ew.theitroad.com
In this program, we use the java.time.LocalDate
class to represent the two dates. We create two LocalDate
objects using the parse
method of the DateTimeFormatter
class, which allows us to convert strings into dates. We then use the plusDays
, plusMonths
, and plusYears
methods of the LocalDate
class to add the two dates together, and store the result in a new LocalDate
object.
Finally, we use the format
method of the DateTimeFormatter
class to convert the resulting LocalDate
object back into a string in ISO date format, which we print to the console.