【问题标题】:Kotlin, iteration through calendar: is it possible?Kotlin,通过日历迭代:有可能吗?
【发布时间】:2021-02-04 12:15:15
【问题描述】:

我正在探索 kotlin(在 Android 工作室)中通过日历循环的潜力。特别是我想在两个固定日期之间的每一天执行一次操作。 我见过与 java.time.LocalDate 类似的东西( while (date.isBefore(endDate)) ..{} )。 您认为日历也可以吗? 任何建议将不胜感激。 谢谢

【问题讨论】:

  • 我不太确定我是否了解您的用例。你真的想让你的程序一直运行,而每天只做一次吗?您没有任何调度设施可供您使用吗?另外我建议使用kotlin.timejava.time 而不是Calendar,为什么你特别需要Calendar
  • 亲爱的 Joffrey,谢谢您,程序只会在单击按钮时执行此计算。在应用程序中,用户可以设置日期,当单击此按钮时,程序应考虑插入日期和固定日期之间的每一天进行计算 - 例如,程序可以更改另一个变量的值,添加一个值取决于初始日期和结束日期之间的每个特定日期。
  • 哦,好吧,我想我明白了。您基本上只想访问此类日期的序列/列表,而不是在这些日期的实际日期执行操作。所以是的,我的问题仍然存在,为什么使用 Calendar 而不是更新的日期时间 API?
  • 感谢 Joffrey 的建议,使用 Localdate 和迭代器解决。我在外部网站上找到了一个有用的解决方案,我可以在这里发布链接吗?
  • 您应该使用 sn-p 代码(作为实际答案)来回答自己,而不是发布链接。这可能会在未来帮助其他人

标签: loops date kotlin calendar iteration


【解决方案1】:

我发现这段代码非常适合我的情况;我在下面报告它,希望它对其他人也有用。

class DateIterator(val startDate: LocalDate,
               val endDateInclusive: LocalDate,
               val stepDays: Long): Iterator<LocalDate> {
private var currentDate = startDate

override fun hasNext() = currentDate <= endDateInclusive

override fun next(): LocalDate {

    val next = currentDate

    currentDate = currentDate.plusDays(stepDays)

    return next

}

}
    class DateProgression(override val start: LocalDate,
                  override val endInclusive: LocalDate,
                  val stepDays: Long = 1) : 
                               Iterable<LocalDate>, ClosedRange<LocalDate> {

override fun iterator(): Iterator<LocalDate> = 
                                  DateIterator(start, endInclusive, stepDays)

infix fun step(days: Long) = DateProgression(start, endInclusive, days)

    }

    operator fun LocalDate.rangeTo(other: LocalDate) = DateProgression(this, other)

    val startDate = LocalDate.of(2021, 1, 1)

    val endDate = LocalDate.of(2021, 1, 31)

    for (date in startDate..endDate step 1) {

        // do something

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 2023-03-12
    相关资源
    最近更新 更多