我在Scala中使用Java的Java .util.Date类,并希望比较Date对象和当前时间。我知道我可以通过使用getTime()来计算delta:
(new java.util.Date()).getTime() - oldDate.getTime()
然而,这只给我留下一个长表示毫秒。有没有更简单,更好的方法来得到时间?
我在Scala中使用Java的Java .util.Date类,并希望比较Date对象和当前时间。我知道我可以通过使用getTime()来计算delta:
(new java.util.Date()).getTime() - oldDate.getTime()
然而,这只给我留下一个长表示毫秒。有没有更简单,更好的方法来得到时间?
当前回答
我喜欢基于timeunit的方法,直到我发现它只覆盖了一个时间单元在下一个更高单位中有多少个单位是固定的这种微不足道的情况。当你想知道间隔了多少个月、多少年等时,这个问题就不成立了。
这里有一种计数方法,不像其他方法那么有效,但它似乎对我有用,而且还考虑到了夏令时。
public static String getOffsetAsString( Calendar cNow, Calendar cThen) {
Calendar cBefore;
Calendar cAfter;
if ( cNow.getTimeInMillis() < cThen.getTimeInMillis()) {
cBefore = ( Calendar) cNow.clone();
cAfter = cThen;
} else {
cBefore = ( Calendar) cThen.clone();
cAfter = cNow;
}
// compute diff
Map<Integer, Long> diffMap = new HashMap<Integer, Long>();
int[] calFields = { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND};
for ( int i = 0; i < calFields.length; i++) {
int field = calFields[ i];
long d = computeDist( cAfter, cBefore, field);
diffMap.put( field, d);
}
final String result = String.format( "%dY %02dM %dT %02d:%02d:%02d.%03d",
diffMap.get( Calendar.YEAR), diffMap.get( Calendar.MONTH), diffMap.get( Calendar.DAY_OF_MONTH), diffMap.get( Calendar.HOUR_OF_DAY), diffMap.get( Calendar.MINUTE), diffMap.get( Calendar.SECOND), diffMap.get( Calendar.MILLISECOND));
return result;
}
private static int computeDist( Calendar cAfter, Calendar cBefore, int field) {
cBefore.setLenient( true);
System.out.print( "D " + new Date( cBefore.getTimeInMillis()) + " --- " + new Date( cAfter.getTimeInMillis()) + ": ");
int count = 0;
if ( cAfter.getTimeInMillis() > cBefore.getTimeInMillis()) {
int fVal = cBefore.get( field);
while ( cAfter.getTimeInMillis() >= cBefore.getTimeInMillis()) {
count++;
fVal = cBefore.get( field);
cBefore.set( field, fVal + 1);
System.out.print( count + "/" + ( fVal + 1) + ": " + new Date( cBefore.getTimeInMillis()) + " ] ");
}
int result = count - 1;
cBefore.set( field, fVal);
System.out.println( "" + result + " at: " + field + " cb = " + new Date( cBefore.getTimeInMillis()));
return result;
}
return 0;
}
其他回答
public static void main(String[] args) {
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/14/2012 10:31:48";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
DateTime date11 = new DateTime(d1);
DateTime date22 = new DateTime(d2);
int days = Days.daysBetween(date11.withTimeAtStartOfDay(), date22.withTimeAtStartOfDay()).getDays();
int hours = Hours.hoursBetween(date11, date22).getHours() % 24;
int minutes = Minutes.minutesBetween(date11, date22).getMinutes() % 60;
int seconds = Seconds.secondsBetween(date11, date22).getSeconds() % 60;
if (hours > 0 || minutes > 0 || seconds > 0) {
days = days + 1;
}
System.out.println(days);
} catch (Exception e) {
e.printStackTrace();
}
}
这将为同一天提供日期差异
如果你不想使用JodaTime或类似的,最好的解决方案可能是:
final static long MILLIS_PER_DAY = 24 * 3600 * 1000;
long msDiff= date1.getTime() - date2.getTime();
long daysDiff = Math.round(msDiff / ((double)MILLIS_PER_DAY));
每天的毫秒数并不总是相同的(因为日光节约时间和闰秒),但它非常接近,至少由于日光节约时间的偏差在较长时间内抵消了。因此,除法和舍入将给出正确的结果(至少只要所使用的本地日历不包含DST和闰秒以外的奇怪时间跳转)。
请注意,这仍然假设date1和date2被设置为一天中的同一时间。对于一天中的不同时间,你首先必须定义“日期差异”的含义,正如乔恩·斯基特指出的那样。
另一个纯Java变体:
public boolean isWithin30Days(Calendar queryCalendar) {
// 1. Take the date you are checking, and roll it back N days
Calendar queryCalMinus30Days = Calendar.getInstance();
queryCalMinus30Days.setTime(queryCalendar.getTime());
queryCalMinus30Days.add(Calendar.DATE, -30); // subtract 30 days from the calendar
// 2. Get respective milliseconds for the two Calendars: now & queryCal minus N days
long nowL = Calendar.getInstance().getTimeInMillis();
long queryCalMinus30DaysL = queryCalMinus30Days.getTimeInMillis();
// 3. if nowL is still less than the queryCalMinus30DaysL, it means queryCalendar is more than 30 days into future
boolean isWithin30Days = nowL >= queryCalMinus30DaysL;
return isWithin30Days;
}
感谢这里的入门代码:https://stackoverflow.com/a/30207726/2162226
在java中有一个简单的方法来做到这一点
//创建一个实用方法
public long getDaysBetweenDates(Date d1, Date d2){
return TimeUnit.MILLISECONDS.toDays(d1.getTime() - d2.getTime());
}
该方法将返回两个日期之间的天数。您可以使用默认的java日期格式,也可以轻松地从任何日期格式转换。
不幸的是,JDK Date API被严重破坏了。我推荐使用Joda Time库。
Joda Time有一个时间间隔的概念:
Interval interval = new Interval(oldTime, new Instant());
编辑:顺便说一下,Joda有两个概念:Interval表示两个时间瞬间之间的时间间隔(表示上午8点到上午10点之间的时间),Duration表示没有实际时间边界的时间长度(例如表示两个小时!)
如果你只关心时间比较,大多数Date实现(包括JDK)实现了Comparable接口,允许你使用Comparable. compareto ()