[英]How do I convert a Firestore date/Timestamp to Date in Kotlin?
[英]How to sort date Firestore in Kotlin?
我想列出最新的订单,直到最旧的订单。 我已经在用户付款之前设置了日期格式。
// 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)
}
}
我的日期输出如 2021 年 6 月 6 日,10:50 -> 2021 年 11 月 5 日,14:22 -> 2021 年 5 月 3 日,10:58 -> 2021 年 4 月 3 日,09:13
如何从最新到最旧对日期进行排序并将其列出到我的 RecyclerView 中?
我会在 Firestore 中再添加一个字段,它接受以毫秒为单位的Unix 时间。 让我们调用order_created_date
。 然后在检索订单列表时,您可以使用相同的orderBy("order_created_date",Query.Direction.DESCENDING)
方法。 在这种情况下,它将比较数字。
我还建议使用这种获取当前时间的方法
val currentDateTime = Calendar.getInstance()
currentDateTime.timeInMillis
由于您的方法LocalDateTime.now()
需要 API 级别 26 或更高级别。
问候。
您没有得到所需的结果,因为文档中的date
字段是一个字符串,并且当您对字符串进行排序时,该顺序是lexicographical 。
要解决这个问题,您必须将字段的类型更改为Firestore Timestamp ,然后您的查询将按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.