【问题标题】:Filter the arraylist by subtracting with minutes in kotlin通过在kotlin中减去分钟来过滤arraylist
【发布时间】:2022-01-23 17:34:56
【问题描述】:

我有一个对象列表,在该对象中我有一个值时间戳,它在“时间戳”中:“2021-12-16T07:30:13.950774575Z”,这种格式。当我点击一个名为 60 mins 的文本视图时,我有一个要求,我应该从结束时间获取 60 分钟的数据,也就是说,如果我在下午 4 点到晚上 7 点之间有数据,点击时我需要从下午 6 点到晚上 7 点的数据。那需要减去 1 小时并过滤数据,我已经尝试过但我没有得到正确的解决方案,任何人都可以帮助我如何实现它。请帮助我,因为我是初学者。

【问题讨论】:

  • 你能告诉我们你到目前为止所做的尝试吗?

标签: android date kotlin arraylist


【解决方案1】:

将所有数据放在一个列表中,然后过滤列表中最近 60 分钟内的元素。

var now = currentTS();
var l = listOf(parseTS("2021-12-16T07:30:13.950774575Z"), parseDate(...),...);
var result = l.filter { it.inMinutes() - now.inMinutes() < 60 }

我不知道您使用的是哪种时间戳类,因此请根据您的需要调整currentTSparseTSinMinutes

【讨论】:

    【解决方案2】:

    我会使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      相关资源
      最近更新 更多