在Java中求和两个日期

Sum two dates in Java(在Java中求和两个日期)
本文介绍了在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).

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Month is not printed from a date - Java DateFormat(月份不是从日期打印的 - Java DateFormat)
java get week of year for given a date(java获取给定日期的一年中的一周)
Get the number of days, weeks, and months, since Epoch in Java(获取自 Java 中的 Epoch 以来的天数、周数和月数)
Is there a good way to get the date of the coming Wednesday?(有什么好方法可以得到即将到来的星期三的日期吗?)
Calendar view for Android GingerBread and before (APIlt;11)(Android GingerBread 及之前的日历视图 (API11))
How to save and retrieve Date in SharedPreferences(如何在 SharedPreferences 中保存和检索日期)