Add Two Dates in Java


In this tutorial, we will discuss to add two dates in Java using Calendar. The below program will show the c1 and c2 that stores the current date. Then, we simply duplicate or cloning c1 and add c2’s each DateTime properties one after the other.

Example: Add Two Dates

import java.util.Calendar;

public class DateTimeComputation {
    public static void main(String[] args) {
    public static void addTwoDates(){
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        Calendar cTotal = (Calendar) c1.clone();
        cTotal.add(Calendar.YEAR, c2.get(Calendar.YEAR));
        cTotal.add(Calendar.MONTH, c2.get(Calendar.MONTH) + 1); // Zero-based months
        cTotal.add(Calendar.DATE, c2.get(Calendar.DATE));
        cTotal.add(Calendar.HOUR_OF_DAY, c2.get(Calendar.HOUR_OF_DAY));
        cTotal.add(Calendar.MINUTE, c2.get(Calendar.MINUTE));
        cTotal.add(Calendar.SECOND, c2.get(Calendar.SECOND));
        cTotal.add(Calendar.MILLISECOND, c2.get(Calendar.MILLISECOND));
        System.out.format("%s + %s = %s", c1.getTime(), c2.getTime(), cTotal.getTime());

The output program will be:

Sun Sep 29 18:30:46 ICT 2019 + Sun Sep 29 18:30:46 ICT 2019 = Fri Jul 29 13:01:32 ICT 4039

For another java tutorial, you can find it through this link.

Back To Top