In Java, it is possible to add two dates together by using the Calendar class.
This class provides methods to add or subtract values from specific fields of a given date.
Here is a simple program to add two dates:
import java.util.Calendar; import java.util.Date; public class AddTwoDates { public static void main(String[] args) { Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); Date date1 = new Date(2022, 1, 1); Date date2 = new Date(2023, 1, 1); cal1.setTime(date1); cal2.setTime(date2); cal1.add(Calendar.DATE, cal2.get(Calendar.DATE)); cal1.add(Calendar.MONTH, cal2.get(Calendar.MONTH)); cal1.add(Calendar.YEAR, cal2.get(Calendar.YEAR)); Date resultDate = cal1.getTime(); System.out.println(resultDate); } }
In this program, we create two instances of the Calendar class, cal1
and cal2
, and two instances of the Date class, date1
and date2
.
We then set the time of each Calendar instance to the corresponding date using the setTime
method.
Next, we add the values of each field of cal2
to the corresponding field of cal1
using the add
method.
Finally, we get the resulting date by calling the getTime
method of cal1
and print it to the console using System.out.println
.
Note that the Date
constructor used in this program is deprecated and it is recommended to use the Calendar
class instead to create dates.