代码之家  ›  专栏  ›  技术社区  ›  s1m0nw1

Kotlin:如何在Joda间隔内迭代所有日期?

  •  5
  • s1m0nw1  · 技术社区  · 6 年前

    我想迭代给定Joda间隔内的所有日期:

    val interval = Interval(DateTime.now().minusDays(42), DateTime.now())
    

    在科特林怎么做?

    4 回复  |  直到 6 年前
        1
  •  4
  •   Roland    6 年前

    深受您当前解决方案的启发:

    fun Interval.toDateTimes() = generateSequence(start) { it.plusDays(1) }
                                                     .takeWhile(::contains) 
    

    interval.toDateTimes()
            .forEach { println(it) }
    

    如果你需要 LocalDate 您仍然可以执行以下操作:

    interval.toDateTimes()
            .map(DateTime::toLocalDate)
            .forEach { println(it) }
    

    Interval 再一次:

    fun Interval.toLocalDates() = toDateTimes().map(DateTime::toLocalDate)
    

    如果希望结束日期包含在内,请使用 takeWhile { it <= end }

        2
  •  3
  •   s1m0nw1    6 年前

    下面的扩展函数给出 Sequence 属于 LocalDate 来自给定 Interval ,可用于迭代这些日期。

    fun Interval.toLocalDates(): Sequence<LocalDate> = generateSequence(start) { d ->
        d.plusDays(1).takeIf { it < end }
    }.map(DateTime::toLocalDate)
    

    用法:

    val interval = Interval(DateTime.now().minusDays(42), DateTime.now())
    interval.toLocalDates().forEach {
        println(it)
    }
    

    在这个解决方案中,最后一天, DateTime.now() 顺序 间隔 也实施了:

    “时间间隔表示两个瞬间之间的一段时间。间隔包括开始时刻,不包括结束时刻。”

    如果出于任何原因,你想让它包括最后一天,只需更改 takeIf 条件到 it <= end .

        3
  •  3
  •   Pavel    6 年前

    for (i in LocalDate.now() .. LocalDate.now().plusWeeks(1)) {
        System.out.print(i) // 2018-08-30 2018-08-31 2018-09-01 
    }
    

    以下是操作员分机代码:

    operator fun LocalDate.rangeTo(other: LocalDate): LocalDateRange {
        return LocalDateRange(this, other)
    }
    

    class LocalDateRange(override val start: LocalDate, override val endInclusive: LocalDate)
        : ClosedRange<LocalDate>, Iterable<LocalDate> {
        override fun iterator(): Iterator<LocalDate> {
            return DateIterator(start, endInclusive)
        }
    }
    
    class DateIterator(start: LocalDate, private val endInclusive: LocalDate)
        : Iterator<LocalDate> {
    
        private var current = start
    
        override fun hasNext(): Boolean {
            return current <= endInclusive
        }
    
        override fun next(): LocalDate {
            current = current.plusDays(1)
            return current
        }
    }
    
        4
  •  0
  •   marc_s    6 年前

    LocalDate 是现在的首选,所以我们可以简单地以天作为数字进行迭代:

    for (day in minDate.toEpochDay()..maxDate.toEpochDay()) {
        // ...
    }
    

    或:

    (minDate.toEpochDay()..maxDate.toEpochDay()).forEach {
        // ...
    }
    

    generateSequence(minDate) { it.plusDays(1) }.takeWhile { it < maxDate }.forEach {
        // it ...
    }
    

    或:

    var day = minDate;
    while (day < maxDate) {
        day = day.plusDays(1);
        // ...
    }