在Java中总计两个日期 [英] Sum two dates in Java

查看:130
本文介绍了在Java中总计两个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I add two dates in Java?

示例:2010-01-14 19:16:170000-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.

更新:对于日历,我将执行以下操作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);

UPDATED:如Steve所述,如果您在此提供的日期假设第​​二个日期是尊重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).

这篇关于在Java中总计两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆