Sum two dates in 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中求和两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在Java中求和两个日期
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01