在Java中求和两个日期

2022-01-11 00:00:00 date calendar java

如何在 Java 中添加两个日期?

How can I add two dates in Java?

示例:2010-01-14 19:16:17"0000-10-03 01:10:05"之和
将导致2010-11-17 20:26:22".

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 to do it using Calendar and adding field by field.

还有其他方法可以一次将它们全部(年/月/日/小时/分钟/秒)求和吗?

Is any other way to sum them all (year/month/day/hour/minute/second) at once?

推荐答案

如果你使用的是 Date 对象,你可以这样做:

If you are using the Date object, you can just do:

Date d1 = ...
Date d2 = ...

long sum = d1.getTime() + d2.getTime();

Date sumDate = new Date(sum);

代码使用 .getTime() 方法返回自纪元以来的毫秒数.不用说 Date 类有很多问题,应该尽可能避免.

The code uses the .getTime() method that returns the number of milliseconds since the epoch. Needless to say the Date class has a lot of problems and should be avoided when possible.

您想对其他类型求和吗?

Do you want to sum other types instead?

更新:对于 Calendar,我会执行以下操作(基于 javadocs):

Update: for Calendar, I would do the following (based on javadocs):

Calendar c1 = ...
Calendar c2 = ...
long sum = c1.getTimeInMillis() + c2.getTimeInMillis();
Calendar sumCalendar = (Calendar)c1.clone();
sumCalendar.setTimeInMillis(sum);

更新:正如史蒂夫所说,如果您在此处提供的日期假定第二个日期与 Java 纪元有关,则此方法有效.如果您确实想从0"年开始,那么您需要考虑这一点(通过减去您的纪元时间).

UPDATED: As Steve stated, this works if the Date you presented here assumes that the second date is with respect to the Java epoch. If you do want to start with year "0", then you need to account for that (by subtracting your epoch time).

相关文章