使用JodaTime我目前正在检查开始日期和结束日期之间的天数,如下所示:
todayDate = new DateTime();
expiryDate = new DateTime(dbReportModel.getValidityTime());
lastDate = new DateTime(dbReportModel.getLastDate());
Days dayDifference = Days.daysBetween(new LocalDate(todayDate), new LocalDate(expiryDate));
如果上述天差异小于或等于某些int
天,我会开始通知我的用户:
if (dayDifference.getDays() <= expiryNotificationProperties.getDaysBefore())
该计划每天都在运行。问题是我不需要每天发送信息。我只需要通知每个f.e. 15天。
目前我有这种方法使用间隔来获取给定开始日期和结束日期之间的日期列表:
private List<LocalDate> getDatesBetweenExpiryDateTodayDate (DateTime todayDate, DateTime expiryDate, int interval) {
List<LocalDate> listOfDatesWithInterval = new ArrayList <>();
int numberOfDays = Days.daysBetween(new LocalDate(todayDate), new LocalDate(expiryDate)).getDays();
LocalDate dynamicExpiryDate = expiryDate.toLocalDate();
while (numberOfDays > 0) {
listOfDatesWithInterval.add(dynamicExpiryDate.minusDays(interval));
dynamicExpiryDate = dynamicExpiryDate.minusDays(interval);
numberOfDays -= interval;
}
return listOfDatesWithInterval;
}
这是额外的检查,今天的日期在列表中:
List<LocalDate> listOfDatesUsingInterval = getDatesBetweenExpiryDateTodayDate(todayDate, expiryDate, interval);
if (listOfDatesUsingInterval.contains(todayDate.toLocalDate())) {
是否有可能以更好的方式在JodaTime中执行此操作?是否有内置的功能来实现这一结果?
答案 0 :(得分:2)
如果您无法使用Java8,请尝试使用Google Guava:
private static void getDays(DateTime todayDate, DateTime expiryDate, int interval) {
int numberOfDays = Days.daysBetween(new LocalDate(todayDate), new LocalDate(expiryDate)).getDays();
Range<Integer> open = Range.closed(1, numberOfDays/interval);
ImmutableList<Integer> integers = ContiguousSet.create(open, DiscreteDomain.integers()).asList();
FluentIterable.from(integers).transform(new ConvertToDate(interval)).toList().forEach(System.out::println);
}
private static class ConvertToDate implements Function<Integer, DateTime> {
private final int interval;
public ConvertToDate(int interval) {
this.interval = interval;
}
@Override
public DateTime apply(Integer integer) {
return DateTime.now().plusDays(integer* interval);
}
}
我不知道这是否是更好的解决方案,但我发现它更容易阅读。
答案 1 :(得分:1)
您可以使用流
int numberOfDays = Days.daysBetween(LocalDate.now(), LocalDate.now().plusDays(10)).getDays();
List<LocalDate> collect = Stream.iterate(LocalDate.now(), e -> e.plusDays(1)).limit(numberOfDays).collect(Collectors.toList());
collect.forEach(System.out::println);