You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于指定递归规则生成给定时间范围内的日期列表?

方案建议

不需要完全自行实现底层日期逻辑,直接用官方提供的日期处理库即可规避闰月、闰年、大小月等边界问题:

  • Kotlin/JVM 环境直接用 JDK 8+ 内置的 java.time 包,无额外依赖
  • 多平台场景可以用官方维护的 kotlinx-datetime 库,API 和 java.time 设计基本一致

第一步:先实现自定义Date类和官方日期类的互转

import java.time.DayOfWeek
import java.time.LocalDate

// 自定义Date转JDK LocalDate
fun Date.toLocalDate(): LocalDate = LocalDate.of(year, month, day)
// JDK LocalDate转回自定义Date
fun LocalDate.toCustomDate(): Date = Date(dayOfMonth, monthValue, year)

第二步:完整函数实现

fun createListOfEvents(startDate: Date, endDate: Date, recursion: Recursion): List<Date> {
    val startLd = startDate.toLocalDate()
    val endLd = endDate.toLocalDate()
    // 起始日期晚于结束日期直接返回空列表
    if (startLd.isAfter(endLd)) return emptyList()

    val result = mutableListOf<Date>()
    var currentLd = startLd

    while (!currentLd.isAfter(endLd)) {
        when (recursion) {
            Recursion.NEVER -> {
                result.add(currentLd.toCustomDate())
                break // 仅返回起始日期,直接结束循环
            }
            Recursion.EVERY_DAY -> {
                result.add(currentLd.toCustomDate())
                currentLd = currentLd.plusDays(1)
            }
            Recursion.EVERY_WORK_DAY -> {
                // 默认过滤周六周日,如需适配法定节假日/调休,可在此处新增自定义判断逻辑
                if (currentLd.dayOfWeek !in setOf(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY)) {
                    result.add(currentLd.toCustomDate())
                }
                currentLd = currentLd.plusDays(1)
            }
            Recursion.EVERY_WEEK -> {
                result.add(currentLd.toCustomDate())
                currentLd = currentLd.plusWeeks(1)
            }
            Recursion.EVERY_MONTH -> {
                result.add(currentLd.toCustomDate())
                // 自动处理月末边界:比如1月31日加1个月会自动适配为2月最后一天
                currentLd = currentLd.plusMonths(1)
            }
            Recursion.ANNUAL -> {
                result.add(currentLd.toCustomDate())
                // 自动处理闰年边界:2月29日加1年,非闰年时会自动适配为2月28日
                currentLd = currentLd.plusYears(1)
            }
        }
    }
    return result
}

额外说明

如果业务场景需要支持更复杂的重复规则(比如每周一和周三、每月第二个周五等),可以基于上述逻辑扩展Recursion枚举的字段,新增规则判断逻辑即可,不需要修改底层日期计算的部分。

内容的提问来源于stack exchange,提问作者Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:30:00