简体   繁体   中英

How to sort date Firestore in Kotlin?

I want to list out the newest order until the oldest order. I have set the date format before the users do payments.

// 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)

After the users do the payment, it will add to my Firestore. When I retrieve the data, it's only descending my date of the month.

    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 data structure

My date output like 06 Jun 2021, 10:50 -> 05 Nov 2021, 14:22 -> 03 May 2021, 10:58 -> 03 Apr 2021, 09:13

Date image result

How can I get sort the date from newest until oldest and list it out into my RecyclerView?

I would add one more field in the Firestore, which accepts Unix time in milliseconds. Let's call order_created_date . Then while retrieving the list of the Orders, you can use the same orderBy("order_created_date",Query.Direction.DESCENDING) method. In that case it will compare numbers.

I would also suggest using this approach of getting current time

val currentDateTime = Calendar.getInstance()
currentDateTime.timeInMillis

As your method LocalDateTime.now() requires API level 26 or above.

Regards.

You aren't getting the desired results because the date field inside the document is a String, and when you order strings, the order is lexicographical .

To solve this, you have to change the type of the field to be a Firestore Timestamp , and then your query will work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM