【问题标题】:How do I sort date components in Swift?如何在 Swift 中对日期组件进行排序?
【发布时间】:2019-11-01 08:01:14
【问题描述】:

我想按初始格式为yyyy-MM-dd'T'HH:mm:ss.SSSZ 的日期对数据进行分组,并显示为E, dd MMM。我设法按日期对它们进行分组,但未能按降序对日期进行排序。在字典中分组后如何对日期组件进行排序?

JSON 响应

{
    "list": [
        {
            "userId": "test1",
            "transactionTime": "2019-06-20T14:01:00.253+08:00"
        },
        {
            "userId": "test2",
            "transactionTime": "2019-06-16T14:02:00.253+08:00"
        },
        {
            "userId": "test3",
            "transactionTime": "2019-06-12T14:01:00.253+08:00"
        },
        {
            "userId": "tes4",
            "transactionTime": "2019-06-17T14:02:00.253+08:00"
        },
    ]
}

分组

func convertToDateObj() -> Date {
        let dateFormatter = DateFormatter()

        // Convert from initial date string to date object
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        let dateObj = dateFormatter.date(from: self)!
        return dateObj
    }


// Group list by date
let groupedList = Dictionary(grouping: rawTransactionsList, by: { list -> DateComponents in
    let dateObj = list.transactionTime.convertToDateObj()
    let date = Calendar.current.dateComponents([.day, .month], from: (dateObj))
    return date
})

// QUESTION
// How do I sort the keys?
// groupList.keys.sorted(...)?

// Populate my list with grouped list
groupedList.keys.forEach { key in
    print("Group keys \(key)")
    let values = groupedList[key]
    groupedtransactionsList.append(values ?? [])
}

【问题讨论】:

  • 为什么只按日和月分组,而不按年分组?不同年份的同一天将进入同一组。这是故意的吗?
  • 您的字典将以DateComponents 为关键字。最好按Date 分组。另外,为什么需要convertToDateObj 函数来进行分组?您的结构应该已经有一个 Date 属性,而不是字符串。解码 JSON 时自动执行该转换。
  • @Sweeper,这不是故意的,我也应该考虑年份,但是如何对键进行排序? @rmaddy 我明白,如果是Date 格式,我该如何进行分组和排序?

标签: ios swift sorting date nsdatecomponents


【解决方案1】:

您可能还应该按年份分组,否则不同年份的同一天将在同一组中:

let date = Calendar.current.dateComponents([.day, .month, .year], from: (dateObj))

对键进行排序的一种方法是将日期组件转换回Dates,使用Calendar.current.date(from:)

let sortedList = groupedList.sorted {
    Calendar.current.date(from: $0.key) ?? Date.distantFuture <
        Calendar.current.date(from: $1.key) ?? Date.distantFuture
}

sortedList.forEach { key, values in
    print("Group keys \(key)")
    groupedtransactionsList.append(values ?? [])
}

【讨论】:

  • sortedList没有keys的成员,应该是sortedList.forEach { ... }dateComponents([.day, .month, .year]
  • @SamuelKith 我的意思是sortedList.forEach。糟糕!
【解决方案2】:

我的建议是使用格式为yyyy-MM-dd 的日期字符串作为字典键而不是日期组件。这个字符串可以排序。

let groupedList = Dictionary(grouping: rawTransactionsList, by: { list -> String in
    let dateObj = list.transactionTime.convertToDateObj()
    let comps = Calendar.current.dateComponents([.day, .month, .year], from: dateObj)
    return String(format: "%ld-%.2ld-%.2ld", comps.year!, comps.month!, comps.day!)
})

groupedtransactionsList = groupedList.keys.sorted(by: >).map { groupedList[$0]! }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-23
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 2023-03-04
    • 2010-10-10
    • 2014-07-08
    相关资源
    最近更新 更多