[Link].
com /java-programming/examples/add-two-dates
Java Program to Add Two Dates
2-3 minutes
In this program, you'll learn to add two dates in Java using Calendar.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Class and Objects
Java Basic Input and Output
Since, Java epoch is 1970, any time represented in a Date object will not work. This means, your Dates will start
from 1970 and when two Date objects are added, the sum misses by about 1970 years. So, we use Calendar
instead.
Example: Java program to add two dates
import [Link];
public class AddDates {
public static void main(String[] args) {
Calendar c1 = [Link]();
Calendar c2 = [Link]();
Calendar cTotal = (Calendar) [Link]();
[Link]([Link], [Link]([Link]));
[Link]([Link], [Link]([Link]) + 1); // Zero-based
months
[Link]([Link], [Link]([Link]));
[Link](Calendar.HOUR_OF_DAY, [Link](Calendar.HOUR_OF_DAY));
[Link]([Link], [Link]([Link]));
[Link]([Link], [Link]([Link]));
[Link]([Link], [Link]([Link]));
[Link]("%s + %s = %s", [Link](), [Link](),
[Link]());
}
}
Output
Tue Aug 08 10:20:56 NPT 2017 + Tue Aug 08 10:20:56 NPT 2017 = Mon Apr 16 20:41:53
NPT 4035
In the above program, c1 and c2 stores the current date. Then, we simply clone c1 and add c2's each DateTime
properties one after the other.
As you can see, we've added 1 to the months. This is because months start with 0 in Java.
Alternatively, you can also use Joda for time/date operations in Java.