我在Scala中使用Java的Java .util.Date类,并希望比较Date对象和当前时间。我知道我可以通过使用getTime()来计算delta:

(new java.util.Date()).getTime() - oldDate.getTime()

然而,这只给我留下一个长表示毫秒。有没有更简单,更好的方法来得到时间?


当前回答

Since dates can contain hours and minutes, final result will be rounded down, which will result in incorrect value. For example, you calculate difference between today at 22:00 p.m and day after tomorrow 00:00 a.m, so the final result will be 1, because in reality it was 1.08 or smth difference, then it gets rounded down when calling TimeUnit.MILLISECONDS.toDays(..). That's why you need to take that in account, so in my solution I subtract the remainder of milliseconds from milliseconds in a day. Additionally, if you want to count the end date, you need to +1 it.

import java.util.Date;
import java.util.concurrent.TimeUnit;

public static long getDaysBetween(Date date1, Date date2, boolean includeEndDate) {
        long millisInDay = 60 * 60 * 24 * 1000;
        long difference = Math.abs(date1.getTime() - date2.getTime());
        long add = millisInDay - (difference % millisInDay);//is used to calculate true number of days, because by default hours, minutes are also counted

        return TimeUnit.MILLISECONDS.toDays(difference + add) + (includeEndDate ? 1 : 0);
    }

测试:

Date date1 = new Date(121, Calendar.NOVEMBER, 27); //2021 Nov 27
Date date2 = new Date(121, Calendar.DECEMBER, 29); //2021 Dec 29
System.out.println( getDaysBetween(date1, date2, false) ); //32 days difference
System.out.println( getDaysBetween(date1, date2, true) ); //33 days difference

其他回答

不使用标准API,不行。你可以这样做:

class Duration {
    private final TimeUnit unit;
    private final long length;
    // ...
}

或者你可以使用Joda:

DateTime a = ..., b = ...;
Duration d = new Duration(a, b);

以毫秒为单位减去日期是可行的(如另一篇文章所述),但在清除日期的时间部分时,你必须使用HOUR_OF_DAY而不是HOUR:

public static final long MSPERDAY = 60 * 60 * 24 * 1000;
...
final Calendar dateStartCal = Calendar.getInstance();
dateStartCal.setTime(dateStart);
dateStartCal.set(Calendar.HOUR_OF_DAY, 0); // Crucial.
dateStartCal.set(Calendar.MINUTE, 0);
dateStartCal.set(Calendar.SECOND, 0);
dateStartCal.set(Calendar.MILLISECOND, 0);
final Calendar dateEndCal = Calendar.getInstance();
dateEndCal.setTime(dateEnd);
dateEndCal.set(Calendar.HOUR_OF_DAY, 0); // Crucial.
dateEndCal.set(Calendar.MINUTE, 0);
dateEndCal.set(Calendar.SECOND, 0);
dateEndCal.set(Calendar.MILLISECOND, 0);
final long dateDifferenceInDays = ( dateStartCal.getTimeInMillis()
                                  - dateEndCal.getTimeInMillis()
                                  ) / MSPERDAY;
if (dateDifferenceInDays > 15) {
    // Do something if difference > 15 days
}

由于这里所有的答案都是正确的,但使用传统java或第三方库,如joda或类似的,我将放弃使用新java的另一种方式。Java 8及以后版本中的时间类。参见Oracle教程。

使用LocalDate和ChronoUnit:

LocalDate d1 = LocalDate.of(2017, 5, 1);
LocalDate d2 = LocalDate.of(2017, 5, 18);

long days = ChronoUnit.DAYS.between(d1, d2);
System.out.println( days );

不幸的是,JDK Date API被严重破坏了。我推荐使用Joda Time库。

Joda Time有一个时间间隔的概念:

Interval interval = new Interval(oldTime, new Instant());

编辑:顺便说一下,Joda有两个概念:Interval表示两个时间瞬间之间的时间间隔(表示上午8点到上午10点之间的时间),Duration表示没有实际时间边界的时间长度(例如表示两个小时!)

如果你只关心时间比较,大多数Date实现(包括JDK)实现了Comparable接口,允许你使用Comparable. compareto ()

因为这个问题用Scala做了标记,

import scala.concurrent.duration._
val diff = (System.currentTimeMillis() - oldDate.getTime).milliseconds
val diffSeconds = diff.toSeconds
val diffMinutes = diff.toMinutes
val diffHours = diff.toHours
val diffDays = diff.toDays