从范围生成日期

时间:2018-08-23 21:21:30

标签: java java-8

我需要从范围中创建日期。

示例:

Start: 01.01.2017 16:30
End:   04.01.2017 23.30

预期结果:

01.01.2017 16:30
01.01.2017 23:00
01.02.2017 09:00
01.02.2017 23:00
01.03.2017 09:00
01.03.2017 23:00
01.04.2017 09:00
01.04.2017 23:00
01.04.2017 23.30
etc...

还有更好的方法吗?

ZonedDateTime start = ZonedDateTime.now();
ZonedDateTime end = ZonedDateTime.now().plusDays(10);

List<ZonedDateTime> result = new ArrayList();
result.add(start);

while(start.isBefore(end) || start.compareTo(end)==0){
  if(start.getHour == 23 || start.getMinute() == 0){
     result.add(start);
  }
  if(start.getHour == 9 || start.getMinute() == 0){
     result.add(start);
  }
  start = start.addMinutes(1);
}
result.add(end);

2 个答案:

答案 0 :(得分:1)

因此,您说要迭代两个日期之间的时间,并且基于预期的输出,您每天只需要两个特定的时间,这引起了您为何要增加分钟数的疑问。

也许(从概念上)更像...

String startValue = "01.01.2017 16:30";
String endValue = "04.01.2017 23:30";

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("dd.MM.yyyy HH:mm")
        .toFormatter(Locale.UK);

LocalDateTime startDate = LocalDateTime.parse(startValue, formatter);
LocalDateTime endTime = LocalDateTime.parse(endValue, formatter);

List<LocalDateTime> times = new ArrayList<>(10);
for (LocalDateTime time = startDate; time.isBefore(endTime); time = time.plusDays(1)) {
    times.add(time.withHour(16).withMinute(30));
    times.add(time.withHour(23).withMinute(00));
}

for (LocalDateTime zdt : times) {
    System.out.println(formatter.format(zdt));
}

将帮助解决该问题。

这将输出...

01.01.2017 16:30
01.01.2017 23:00
02.01.2017 16:30
02.01.2017 23:00
03.01.2017 16:30
03.01.2017 23:00
04.01.2017 16:30
04.01.2017 23:00

其他解决方案可能是有两个锚定时间,一个锚定时间16:30和一个锚定时间23:00,并在每个循环中将它们简单地增加一天

答案 1 :(得分:-1)

您可以使用“持续时间”来实现。该类提供对LocalTime,ZonedDateTime或LocalDateTime对象的操作。

示例:

Duration daily = Duration.ofDays(1);
Duration hourly = Duration.ofHours(1);

使用一些小算法和此类,您应该完成自己的目标。

算法示例,根据需要进行修改:开始定义您是在9:00之前还是23:00之前,在最接近的位置创建您的第一个ZonedDateTime,创建从9:00到23的持续时间,然后是第二个到23:00到9:00,然后进行迭代直到您达到结束日期,并在每次迭代时创建ZonedDateTime对象。

相关问题