我在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()
然而,这只给我留下一个长表示毫秒。有没有更简单,更好的方法来得到时间?
当前回答
查看示例http://www.roseindia.net/java/beginners/DateDifferent.shtml 这个例子给出了天、小时、分钟、秒和毫秒的差异:)。
import java.util.Calendar;
import java.util.Date;
public class DateDifferent {
public static void main(String[] args) {
Date date1 = new Date(2009, 01, 10);
Date date2 = new Date(2009, 07, 01);
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.setTime(date1);
calendar2.setTime(date2);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("\nThe Date Different Example");
System.out.println("Time in milliseconds: " + diff + " milliseconds.");
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
System.out.println("Time in days: " + diffDays + " days.");
}
}
其他回答
因为这个问题用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
使用java。Java 8+内置的时间框架:
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime oldDate = now.minusDays(1).minusMinutes(10);
Duration duration = Duration.between(oldDate, now);
System.out.println("ISO-8601: " + duration);
System.out.println("Minutes: " + duration.toMinutes());
输出:
ISO-8601: PT24H10M 分钟:罢工,
有关更多信息,请参阅Oracle教程和ISO 8601标准。
因为您正在使用Scala,所以有一个非常好的Scala库Lamma。在南丫岛,你可以直接用-运算符减去日期
scala> Date(2015, 5, 5) - 2 // minus days by int
res1: io.lamma.Date = Date(2015,5,3)
scala> Date(2015, 5, 15) - Date(2015, 5, 8) // minus two days => difference between two days
res2: Int = 7
int daysDiff = (date1.getTime() - date2.getTime()) / MILLIS_PER_DAY;
您可以尝试较早版本的Java。
public static String daysBetween(Date createdDate, Date expiryDate) {
Calendar createdDateCal = Calendar.getInstance();
createdDateCal.clear();
createdDateCal.setTime(createdDate);
Calendar expiryDateCal = Calendar.getInstance();
expiryDateCal.clear();
expiryDateCal.setTime(expiryDate);
long daysBetween = 0;
while (createdDateCal.before(expiryDateCal)) {
createdDateCal.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween+"";
}