我会使用java.time 和……
- 解析从按钮单击收到的
String(当然是模拟的)
- 从值中减去一小时
- 使用结果从示例列表中过滤
在这里,全部在fun main,请阅读cmets:
fun main(args: Array<String>) {
// your example String received on button click
val timestamp = "2021-12-16T07:30:13.950774575Z"
// example values to be filtered
val someObjects = listOf(
SomeObject(0, "2021-12-12T07:30:13.950774575Z"),
SomeObject(1, "2021-12-13T07:30:13.950774575Z"),
SomeObject(2, "2021-12-13T07:30:13.950774575Z"),
SomeObject(3, "2021-12-14T07:30:13.950774575Z"),
SomeObject(4, "2021-12-15T07:30:13.950774575Z"),
// here's the border
SomeObject(5, "2021-12-16T07:30:13.850774575Z"),
SomeObject(6, "2021-12-16T07:30:13.960774575Z"),
SomeObject(7, "2021-12-17T07:30:13.950774575Z"),
SomeObject(8, "2021-12-18T07:30:13.950774575Z")
)
// parse the timestamp captured on button click and subtract an hour
val filterByOdt = OffsetDateTime.parse(timestamp).minusHours(1)
// filter the list using the OffsetDateTime
val filteredObjects = someObjects.filter {
OffsetDateTime.parse(it.timestamp)
.isBefore(filterByOdt)
}
// print the ids of the results
println(filteredObjects.joinToString(", ") { "${it.id}" })
}
我在示例中使用了以下虚拟类。
data class SomeObject(val id: Long, val timestamp: String)
根据需要,过滤后的列表仅包含 5 个SomeObjects,时间戳在timestamp 之前:
0, 1, 2, 3, 4