如何通过递归获取给定范围内的日期列表

How to get the list of dates in a given range with recursion

我想创建一个函数,该函数 returns 给定范围内的日期列表,具有递归功能。我将提供开始日期、结束日期和递归类型。我不知道如何开始。任何的意见都将会有帮助。有没有这方面的图书馆,还是我必须自己做?

data class Date(
    val day: Int,
    val month: Int,
    val year: Int
)

enum class Recursion {
    NEVER,
    EVERY_DAY,
    EVERY_WORK_DAY,
    EVERY_WEEK,
    EVERY_MONTH,
    ANNUAL
}

fun createListOfEvents(startDate: Date, endDate: Date, recursion: Recursion): List<Date>{
}

好吧,基本上这是一个如何做到这一点的例子:

data class Recursion(val field : TemporalUnit, val step: Long)

    val step1Day = Recursion(field = ChronoUnit.DAYS, step = 1)

    fun createListOfEvents(startDate: LocalDate, endDate: LocalDate, recursion: Recursion): List<LocalDate>{
        var currentDate = startDate
        val listOfDates = mutableListOf<LocalDate>()
        while (currentDate.isBefore(endDate)) {
            listOfDates.add(currentDate)
            currentDate = startDate.plus(recursion.step, recursion.field)
        }
        return listOfDates
    }

此方法returns 从 startDate 到 endDate 的日期列表,递归步骤。 如您所见,我为此使用了 java.time.* 类,但最终您可以将它们转换为您自己的日期和递归并返回。 这里 TemporalUnit 可以是 DAYS, WEEKS, MONTHS, YEARS (和其他)。 它涵盖了您的大部分需求,您将不得不手动管理工作日。 希望这是有道理的)

如果目标 SDK < 26,您需要启用 desugaring

然后您可以为此使用 LocalDate class。你的 Date class 有点多余,但如果你想保留它,你可以在函数内部转换为 LocalDate。

fun createListOfEvents(startDate: LocalDate, endDate: LocalDate, recursion: Recursion): List<LocalDate> {
    val step = when (recursion) {
        Recursion.NEVER -> return emptyList()
        Recursion.EVERY_DAY, Recursion.EVERY_WORK_DAY -> Period.ofDays(1)
        Recursion.EVERY_WEEK -> Period.ofWeeks(1)
        Recursion.EVERY_MONTH -> Period.ofMonths(1)
        Recursion.ANNUAL -> Period.ofYears(1)
    }
    var date = startDate
    val list = mutableListOf<LocalDate>()
    while (date <= endDate) {
        list.add(date)
        date += step
    }
    if (recursion == Recursion.EVERY_WORK_DAY) {
        val weekend = listOf(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY)
        list.removeAll { it.dayOfWeek in weekend }
    }
    return list
}