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

s1m*_*nw1 5 jodatime intervals kotlin

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

val interval = Interval(DateTime.now().minusDays(42), DateTime.now())
Run Code Online (Sandbox Code Playgroud)

如何在Kotlin中做到这一点?

Rol*_*and 5

Heavily inspired by your current solution:

fun Interval.toDateTimes() = generateSequence(start) { it.plusDays(1) }
                                                 .takeWhile(::contains) 
Run Code Online (Sandbox Code Playgroud)

Usage:

interval.toDateTimes()
        .forEach { println(it) }
Run Code Online (Sandbox Code Playgroud)

If you need the LocalDate you could still do the following instead:

interval.toDateTimes()
        .map(DateTime::toLocalDate)
        .forEach { println(it) }
Run Code Online (Sandbox Code Playgroud)

or as an extension function to Interval again:

fun Interval.toLocalDates() = toDateTimes().map(DateTime::toLocalDate)
Run Code Online (Sandbox Code Playgroud)

If you want the end date to be inclusive instead, use takeWhile { it <= end } instead.


s1m*_*nw1 4

以下扩展函数给出了给定的对象Sequence,可用于迭代这些日期。LocalDateInterval

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

用法:

val interval = Interval(DateTime.now().minusDays(42), DateTime.now())
interval.toLocalDates().forEach {
    println(it)
}
Run Code Online (Sandbox Code Playgroud)

在此解决方案中,最后一天DateTime.now()不包含在其中,Sequence因为这也是Interval实现方式:

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

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