Java Program to Add Two Dates

In this java program, we will learn about how to add two dates in Java. Any time expressed in a Date object will not function since the Java epoch is the time passed from mid-night of 01/01/1970 UTC.

Your Dates will therefore begin in 1970, and when two Date objects are combined, the total is off by around 1970 years. Hence, we will use Calander objects to represent two date instants and to add it.

Java Program to Add Two Dates using Calendar class

import java.util.Calendar;

public class AddTwoDates {
  public static void main(String[] args) {

    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal2.add(Calendar.YEAR, 2);

    System.out.println("Date1 : " + cal1.getTime());
    System.out.println("Date2 : " + cal2.getTime());
    // Add Date1 and Date2
    Calendar calSum = (Calendar) cal1.clone();

    calSum.add(Calendar.YEAR, cal2.get(Calendar.YEAR));
    // We have to increment the month field by 1 because month
    // index starts from 0. Jan is 0, Feb is 1, Mar is 3 etc.
    calSum.add(Calendar.MONTH, cal2.get(Calendar.MONTH) + 1);
    calSum.add(Calendar.DATE, cal2.get(Calendar.DATE));
    calSum.add(Calendar.HOUR_OF_DAY, cal2.get(Calendar.HOUR_OF_DAY));
    calSum.add(Calendar.MINUTE, cal2.get(Calendar.MINUTE));
    calSum.add(Calendar.SECOND, cal2.get(Calendar.SECOND));
    calSum.add(Calendar.MILLISECOND, cal2.get(Calendar.MILLISECOND));

    System.out.println("Sum Date :" + calSum.getTime());
  }
}
Output
Date1 : Mon Nov 28 20:42:02 PST 2022
Date2 : Thu Nov 28 20:42:02 PST 2024
Sum Date :Tue Nov 26 17:24:05 PST 4047

In above java program, we created two Calendar objects cal1 and cal2. Object cal1 represent current instant of time whereas cal2 is two year in furure from current time. We inititialize calSum object with a clone of cal1 and add cal2 object one field at a time.