我有一些对象 list 。它们每个都包含指定的特定“开始”和“结束”时间范围。
因此,例如:
import org.joda.time.DateTime
data class MyObject(
val from: String?,
val to: String?
)
asUtcDateTime()
只是我的扩展方法,它将给定的String转换为DateTime我如何找到最近的物体:
到目前为止,我所做的只是从过去和将来获取最近的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/