首页 > 解决方案 > 排序列表基于字符串日期时间

问题描述

我想根据字符串形式的 UTC DateTime 对列表进行降序排序。

我的课

    data class CartEntity( val itemId: String,  var itemName: String, var createdDate: String)

在这个 createdDate 是“2020-07-28T14:28:52.877Z”

我试过的

    const val UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

    Collections.sort(list, object : Comparator<CartEntity> {
        var f: DateFormat =
            SimpleDateFormat(
                AppConstants.UTC_FORMAT, Locale.ENGLISH
            )
    
        override fun compare(o1: CartEntity?, o2: CartEntity?): Int {
            return try {
                val firstitem = f.parse(o1?.createdDate!!)
                val seconditem = f.parse(o2?.createdDate!!)
                firstitem.compareTo(seconditem)
            } catch (e: ParseException) {
                throw IllegalArgumentException(e)
            }
        }
    
    })

但仍然按降序排序没有按预期工作

标签: kotlin

解决方案


在 kotlin 风格中,您可以使用标准库函数(以下习惯用法):

从要排序的列表中创建一个新的排序列表

fun main() {
    val list = listOf<CartEntity>(
        CartEntity(itemId = "", itemName = "", createdDate = "2020-07-28T14:28:52.877Z"),
        CartEntity(itemId = "", itemName = "", createdDate = "2020-09-28T14:28:52.877Z"),
        CartEntity(itemId = "", itemName = "", createdDate = "2020-08-28T14:28:52.877Z"),
        CartEntity(itemId = "", itemName = "", createdDate = "2020-04-28T14:28:52.877Z"),
    )

    val format: DateFormat = SimpleDateFormat(AppConstants.UTC_FORMAT, Locale.ENGLISH)

    val sortedList = list.sortedByDescending { format.parse(it.createdDate) }

    println(sortedList)  // `sortedList` is sorted out list, the `list` is holding the original order
}

对原始列表进行排序(列表应该是可变的):

fun main() {
    val list = mutableListOf<CartEntity>(
        CartEntity(itemId = "", itemName = "", createdDate = "2020-07-28T14:28:52.877Z"),
        CartEntity(itemId = "", itemName = "", createdDate = "2020-09-28T14:28:52.877Z"),
        CartEntity(itemId = "", itemName = "", createdDate = "2020-08-28T14:28:52.877Z"),
        CartEntity(itemId = "", itemName = "", createdDate = "2020-04-28T14:28:52.877Z"),
    )

    val format: DateFormat = SimpleDateFormat(AppConstants.UTC_FORMAT, Locale.ENGLISH)
    list.sortByDescending { format.parse(it.createdDate) }

    println(list)  // `list` is sorted out list
}

推荐阅读