English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to add two dates together in Java using Calendar.
Because the Java era is1970 years, so any time represented by a Date object does not work. This means that your date will start1970 years, when two date objects are added together, the sum will lose approximately1970 years. So, we use Calendar instead.
import java.util.Calendar; public class AddDates { public static void main(String[] args) { 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); // Month starting from zero 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()); } }
When you run the program, the output is:
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, c1and c2. Then, we simply clone c1, and store the current date in c2each DateTime attribute one by one.
As you can see, we increase1This is because the month starts from 0 in Java.