【问题标题】:generating dates from the range [duplicate]从范围内生成日期[重复]
【发布时间】:2019-01-30 08:13:31
【问题描述】:

我需要从范围创建日期。

例子:

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);

【问题讨论】:

  • 什么是时间规则?
  • 模式是什么?
  • 只需添加正确的小时数 - 模式很明显。首先弄清楚如何和第一个间隔之间的区别。然后每次只需移动正确的小时数,直到从开始到 10 天。将比 10 天(10 * 365 * 60 次迭代)一分钟一分钟地迭代快很多
  • 不得不说您的描述与您的预期输出不符,对我来说,所以您只想在给定的天数内将16:3023.30 添加到List ?

标签: java java-8


【解决方案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,并在每个循环中简单地将它们增加一天

【讨论】:

    【解决方案2】:

    您可以使用 Duration 来实现此目的。这是一个提供对 LocalTime、ZonedDateTime 或 LocalDateTime 对象的操作的类。

    例子:

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

    通过一点算法和这个类,你应该可以实现你的目的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 2019-08-25
      相关资源
      最近更新 更多