首页 > 解决方案 > 如何在 Kotlin 中对日期 Firestore 进行排序?

问题描述

我想列出最新的订单,直到最旧的订单。我已经在用户付款之前设置了日期格式。

// Get current date & time
val currentDateTime = LocalDateTime.now()
// Format date time style
currentDateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))
// Finalize convert format
val date = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm").format(currentDateTime)

用户付款后,它会添加到我的 Firestore。当我检索数据时,它只是降低我的月份日期。

    fun getOrderList(activity: Fragment, recyclerView: RecyclerView) {
        mFirestore.collection(Constants.ORDERS)
            .orderBy("date", Query.Direction.DESCENDING)
            .get()
            .addOnSuccessListener { result ->

                val orderItem = result.toObjects(UserOrderList::class.java)
                recyclerView.adapter = OrderListItemAdapter(activity, activity.requireContext(), orderItem)
            }
    }

Firestore 数据结构

我的日期输出如 2021 年 6 月 6 日,10:50 -> 2021 年 11 月 5 日,14:22 -> 2021 年 5 月 3 日,10:58 -> 2021 年 4 月 3 日,09:13

日期图像结果

如何从最新到最旧对日期进行排序并将其列出到我的 RecyclerView 中?

标签: androidfirebasekotlingoogle-cloud-platformgoogle-cloud-firestore

解决方案


您没有得到想要的结果,因为date文档中的字段是一个字符串,并且当您订购字符串时,顺序是lexicographical

要解决这个问题,您必须将字段的类型更改为Firestore Timestamp,然后您的查询将按预期工作。


推荐阅读