Add Two Dates in Java

Exercise:

Write a Java Program to add two dates.

Click Here to View the Solution!
import java.util.Calendar;
public class AddDates {
     public static void main(String[] args) {
 
        Calendar d1 = Calendar.getInstance();
        Calendar d2 = Calendar.getInstance();
        Calendar cTotal = (Calendar) d1.clone();
 
        cTotal.add(Calendar.YEAR, d2.get(Calendar.YEAR));
        cTotal.add(Calendar.MONTH, d2.get(Calendar.MONTH) + 1); 
        // Zero-based months
        cTotal.add(Calendar.DATE, d2.get(Calendar.DATE));
        cTotal.add(Calendar.HOUR_OF_DAY, d2.get(Calendar.HOUR_OF_DAY));
        cTotal.add(Calendar.MINUTE, d2.get(Calendar.MINUTE));
        cTotal.add(Calendar.SECOND, d2.get(Calendar.SECOND));
        cTotal.add(Calendar.MILLISECOND, d2.get(Calendar.MILLISECOND));
        //Display the dates and their sum
        System.out.format("%s + %s = %s", d1.getTime(), d2.getTime(), cTotal.getTime());
 
    }
} 
Click Here to View the Output!
Sat Nov 28 20:28:40 UTC 2020 + Sat Nov 28 20:28:40 UTC 2020 = Tue Nov 26 16:57:20 UTC 4041
Click Here to View the Explanation!
  • This program is used to add two current dates by using the Calendar class in Java.
  • Two Calendar objects d1 and d2 are created. Each of which store the current date.
  • The initial step involves the cloning of the object d1 and copying all the date and time properties of d2 consecutively.
  • The object d1 is cloned and stored in cTotal to which all the d2 properties are added.
  • It is to be noted, since months in Java begin from 0, 1 is added to the get(Calendar, MONTH) method.
  • Finally, the getTime() is used to display the date and time of both the objects d1 and d2 and then sum of the two which was stored in the cTotal object.