0% found this document useful (0 votes)
7 views2 pages

Java Program To Add Two Dates - Reader View

This document provides a Java program example for adding two dates using the Calendar class instead of Date objects to avoid issues with the Java epoch starting in 1970. The program demonstrates how to clone a Calendar instance and add the individual date and time components from another Calendar instance. Additionally, it mentions that Joda can be used as an alternative for date and time operations in Java.

Uploaded by

okstudyshivi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Java Program To Add Two Dates - Reader View

This document provides a Java program example for adding two dates using the Calendar class instead of Date objects to avoid issues with the Java epoch starting in 1970. The program demonstrates how to clone a Calendar instance and add the individual date and time components from another Calendar instance. Additionally, it mentions that Joda can be used as an alternative for date and time operations in Java.

Uploaded by

okstudyshivi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[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.

You might also like