简体   繁体   English

如何在 Swift 中对日期组件进行排序?

[英]How do I sort date components in Swift?

I want to group data by dates which has initial format of yyyy-MM-dd'T'HH:mm:ss.SSSZ and display as E, dd MMM .我想按日期对数据进行分组,该日期的初始格式为yyyy-MM-dd'T'HH:mm:ss.SSSZ并显示为E, dd MMM I have managed to group them by the dates but failed to sort the dates in a descending order.我已设法按日期对它们进行分组,但未能按降序对日期进行排序。 How do I sort the date components after grouping in Dictionary?在字典中分组后如何对日期组件进行排序?

JSON Response 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"
        },
    ]
}

Grouping分组

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 ?? [])
}

You should probably also group by the year, otherwise the same day in different years will be in the same group:您可能还应该按年份分组,否则不同年份的同一天将在同一组中:

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

One way to sort the keys is to convert the date components back into Date s, using Calendar.current.date(from:) :对键进行排序的一种方法是使用Calendar.current.date(from:)将日期组件转换回Date s:

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 ?? [])
}

My suggestion is to use a date string with format yyyy-MM-dd as dictionary key rather than date components.我的建议是使用格式为yyyy-MM-dd的日期字符串作为字典键而不是日期组件。 This string can be sorted.这个字符串可以排序。

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]! }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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