Sum two dates in Java

前端 未结 9 670
夕颜
夕颜 2020-11-27 07:47

How can I add two dates in Java?

Example: The sum of \"2010-01-14 19:16:17\" \"0000-10-03 01:10:05\"
would result in \"2010-11-17 20:26:22\".

I know how

9条回答
  •  再見小時候
    2020-11-27 08:13

    Don't sum the time in millis of the two dates!

    Date d1 = new Date();
    Date d2 = new Date();
    Date dTotal = new Date(d1.getTime() + d2.getTime());
    System.out.println(dTotal); // Incorrect! Misses about 1970 years.
    

    Just clone the Calendar and add the datetime parts one by one.

    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); // Months are zero-based!
    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.println(cTotal.getTime()); // Correct!
    

    Needless to say, JodaTime is smarter and cleaner with this.

提交回复
热议问题