kotlin - 查找距当前日期最近的时间范围

标签 kotlin functional-programming

我有一些对象 list 。它们每个都包含指定的特定“开始”和“结束”时间范围。

因此,例如:

import org.joda.time.DateTime

data class MyObject(
val from: String?,
val to: String?
)
asUtcDateTime()只是我的扩展方法,它将给定的String转换为DateTime

我如何找到最近的物体:
  • 不在今天时间范围
  • 离今天( future 或过去)最近吗?

  • 到目前为止,我所做的只是从过去和将来获取最近的MyObject,如下所示:
        val now = DateTime.now()
    
         val nearestPastSchedule = allSchedules
            .sortedBy { it.to.asUtcDateTime() }
            .filter { it.to.asUtcDateTime() != null }
            .lastOrNull { it.to.asUtcDateTime()!!.millis < now.withTimeAtStartOfDay().millis }
    
        val nearestFutureSchedule = allSchedules
            .sortedBy { it.from.asUtcDateTime() }
            .filter { it.from.asUtcDateTime() != null }
            .lastOrNull { it.from.asUtcDateTime()!!.millis > now.withTimeAtStartOfDay().millis }
    

    不知道从比较它们(考虑到存在可为空)的 Angular 来看什么是好的解决方案,并且还为它们每个返回了实际的MyObject

    最佳答案

    无需排序,您可以自己找到指定的元素。我通过找到现在和对象中指定的时间之间的绝对最小差来做到这一点。

    为简单起见,我将数据类调整为使用ZonedDateTime(假定Java> = 8可用):

        data class MyObject(
                val from: ZonedDateTime?,
                val to: ZonedDateTime?
        )
    

    这样,您可以过滤并找到从现在到相应时间之间的最小绝对值:
    val nearestPastSchedule = 
        allSchedules.filter { it.to != null }
                    .minBy { abs(it.to!!.toInstant().toEpochMilli() - now) }
    val nearestFutureSchedule =
        allSchedules.filter { it.from != null }
                    .minBy { abs(it.from!!.toInstant().toEpochMilli() - now) }
    

    关于kotlin - 查找距当前日期最近的时间范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56221162/

    相关文章:

    android - 如何在 Kotlin 的 fragment 中制作图像列表?

    android - kotlin:使用多个 lambda 调用高阶函数

    android - 继续从回调中挂起函数

    haskell - 什么是更自由的单子(monad)?

    类似 C++ LINQ 的迭代器操作

    java - 查找具有预先计算值的表是 O(1) 算法吗?

    php - 如何访问 "parent"函数的参数?

    performance - 为什么 Dagger 的 Reusable scope 比 Singleton 慢?

    exception - 如何在 Kotlin 中测试预期的未经检查的异常?

    javascript - 在没有 `this` 的情况下访问对象方法