我在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()
然而,这只给我留下一个长表示毫秒。有没有更简单,更好的方法来得到时间?
当前回答
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
其他回答
这是另一个样本。基本上适用于用户定义的模式。
public static LinkedHashMap<String, Object> checkDateDiff(DateTimeFormatter dtfObj, String startDate, String endDate)
{
Map<String, Object> dateDiffMap = new HashMap<String, Object>();
DateTime start = DateTime.parse(startDate,dtfObj);
DateTime end = DateTime.parse(endDate,dtfObj);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
dateDiffMap.put("ISO-8601_PERIOD_FORMAT", period);
dateDiffMap.put("YEAR", period.getYears());
dateDiffMap.put("MONTH", period.getMonths());
dateDiffMap.put("WEEK", period.getWeeks());
dateDiffMap.put("DAY", period.getWeeks());
dateDiffMap.put("HOUR", period.getHours());
dateDiffMap.put("MINUTE", period.getMinutes());
dateDiffMap.put("SECOND", period.getSeconds());
return dateDiffMap;
}
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
public static String getDifferenceBtwTime(Date dateTime) {
long timeDifferenceMilliseconds = new Date().getTime() - dateTime.getTime();
long diffSeconds = timeDifferenceMilliseconds / 1000;
long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
long diffYears = (long)(timeDifferenceMilliseconds / (1000 * 60 * 60 * 24 * 365));
if (diffSeconds < 1) {
return "one sec ago";
} else if (diffMinutes < 1) {
return diffSeconds + " seconds ago";
} else if (diffHours < 1) {
return diffMinutes + " minutes ago";
} else if (diffDays < 1) {
return diffHours + " hours ago";
} else if (diffWeeks < 1) {
return diffDays + " days ago";
} else if (diffMonths < 1) {
return diffWeeks + " weeks ago";
} else if (diffYears < 12) {
return diffMonths + " months ago";
} else {
return diffYears + " years ago";
}
}
另一个纯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
只需在两个Date对象上使用下面的方法。如果你想传递当前日期,只需传递new date()作为第二个参数,因为它是用当前时间初始化的。
public String getDateDiffString(Date dateOne, Date dateTwo)
{
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "dateTwo is " + delta + " days after dateOne";
}
else {
delta *= -1;
return "dateTwo is " + delta + " days before dateOne";
}
}
此外,除了从天数,如果,你也想要其他参数的差异,使用下面的片段,
int year = delta / 365;
int rest = delta % 365;
int month = rest / 30;
rest = rest % 30;
int weeks = rest / 7;
int days = rest % 7;
p.s. Code完全取自SO答案。