問題描述
如何在 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中求和兩個日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!