【问题标题】:How to get a DateTime-Local between two DateTime-Local in java如何在java中的两个DateTime-Local之间获取DateTime-Local
【发布时间】:2018-08-27 12:08:45
【问题描述】:

在how to get a list of dates between two dates in java的回答的帮助下,

如何获取两个 DateTime-Local 之间的 DateTime-Local 列表?

下面是代码

LocalDateTime fromDate = LocalDateTime.parse("2007-12-03T10:15");
LocalDateTime toDate = LocalDateTime.parse("2107-12-03T10:15");

List<LocalDateTime> dates = new ArrayList<LocalDateTime>();

LocalDateTime current = fromDate;

while (current.isBefore(toDate)) {
    dates.add(current);
    current = current.plusDays(1);
}

System.out.println(dates); 

打印出来 [2007-12-03T10:15, 2007-12-04T10:15, 2007-12-05T10:15, 2007-12-06T10:15, 2007-12-07T10:15, 2007-12-08T10:15...

日期增加了一天,但时间没有增加。

如何增加时间?

【问题讨论】:

  • 我不明白预期的输出。假设我们在上午 12 点有了新的日期:你想得到 10+2(从原始日期开始),还是 10+12?能举个例子吗?
  • @Leviand 这两者有区别吗?是的,10+12
  • 我仍然无法得到预期的输出,你上面的例子应该是什么?
  • 不清楚你在问什么。你写了current = current.plusDays(1);,所以日期增加了一天。你还期待什么?如果您希望增加 1 小时,请使用 current = current.plusHours(1);。如果您希望增加 1 分钟,请使用 current = current.plusMinutes(1);。等等。
  • @assylias 抱歉,问题不清楚。写plusDays 是我的错误,您的答案是我正在寻找的,我想按小时递增。谢谢!

标签: java datetime java-time


【解决方案1】:

我猜Spliterator 可以用来检查日期之间的差异。例如,对于每小时增加,HourlySpliterator 可以实现如下:

public class HourlySpliterator implements Spliterator<LocalDateTime>{

private final LocalDateTime endDate;
private LocalDateTime date;

public static Stream<LocalDateTime> of (LocalDateTime startDate,  LocalDateTime endDate) {
    return StreamSupport.stream(new HourlySpliterator(startDate, endDate), false);
}

private HourlySpliterator(LocalDateTime startDate, LocalDateTime endDate) {
    this.date = startDate;
    this.endDate = endDate;
}

@Override
public boolean tryAdvance(Consumer<? super LocalDateTime> action) {
    Objects.requireNonNull(action);
    action.accept(date);
    if (date.isBefore(endDate)) {
        date = date.plusHours(1);
        return true;
    }
    return false;
}

@Override
public Spliterator<LocalDateTime> trySplit() {
    return null;
}

@Override
public long estimateSize() {
    return Long.MAX_VALUE;
}

@Override
public int characteristics() {
    return DISTINCT | IMMUTABLE | NONNULL | ORDERED | SORTED ;
}

@Override
public Comparator<? super LocalDateTime> getComparator() {
   return Comparator.naturalOrder();
}

}

可以这样测试:

@Test
public void test() throws Exception {

        List<LocalDateTime> dates = new ArrayList<LocalDateTime>();

        HourlySpliterator.of(LocalDateTime.parse("2007-12-03T10:15"), LocalDateTime.parse("2007-12-05T10:15"))
        .forEach(dates::add); 

        System.out.println(dates); 


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 2015-04-29
    • 2023-03-21
    • 2014-09-20
    • 2016-12-23
    • 2022-12-14
    • 2019-08-24
    相关资源
    最近更新 更多