我需要在天数中找到当前日期时间LocalDateTIme.now()
与另一个名为LocaDateTime
的{{1}}对象之间的差异。也是从issueDateTime
开始计算的天数。也就是说,如果issueDateTime
是2014年4月12日下午5:00,那么应该计算为每个下午5点而不是上午12点。我想找出发布日期和当前日期之间的差异,然后将其与rentalTariff / day相乘,以返回方法issueDateTime
的金额。谢谢
amountPayable()
答案 0 :(得分:3)
您可以使用ChronoUnit.DAYS
。比较LocalTime
值,看看是否应该考虑开始“第二天”:
import java.time.*;
import java.time.temporal.*;
class Test {
public static void main(String[] args) {
// Start time before end time
showDiff(2014, 9, 25, 15, 0,
2014, 9, 27, 17, 0);
// Start time equal to end time
showDiff(2014, 9, 25, 17, 0,
2014, 9, 27, 17, 0);
// Start time later than end time
showDiff(2014, 9, 25, 18, 0,
2014, 9, 27, 17, 0);
}
public static void showDiff(
int startYear, int startMonth, int startDay,
int startHour, int startMinute,
int endYear, int endMonth, int endDay,
int endHour, int endMinute) {
LocalDateTime start = LocalDateTime.of(
startYear, startMonth, startDay, startHour, startMinute);
LocalDateTime end = LocalDateTime.of(
endYear, endMonth, endDay, endHour, endMinute);
System.out.printf("%s to %s is %d day(s)%n", start, end,
differenceInDays(start, end));
}
public static int differenceInDays(LocalDateTime start, LocalDateTime end) {
LocalDate startDate = start.toLocalDate();
LocalDate endDate = end.toLocalDate();
if (start.toLocalTime().isAfter(end.toLocalTime())) {
startDate = startDate.plusDays(1);
}
return (int) ChronoUnit.DAYS.between(startDate, endDate);
}
}
输出:
2014-09-25T15:00 to 2014-09-27T17:00 is 2 day(s)
2014-09-25T17:00 to 2014-09-27T17:00 is 2 day(s)
2014-09-25T18:00 to 2014-09-27T17:00 is 1 day(s)
答案 1 :(得分:0)
使用LocalDateTime
中的某一天来计算。考虑到原始日期时间可能在当前日期之后,如果年份有差异。 (这将导致负面结果)