DateString 到 timeStamp 以便在 Swift 中排序

DateString to timeStamp for sorting in Swift

我有一个对象数组,其中 dateString(创建)作为参数。我想要 sort 基于 timestamp(创建)的对象数组。

例如,

array = ["dateString":"2018-03-06", "dateString":"2018-03-05"]

考虑到您的数组具有以下格式:

let array: [[String: String]] = [
    ["dateString":"2018-03-06"],
    ["dateString":"2018-03-05"]
]

你应该使用 sorted 方法来获得你需要的东西:

let sortedArray = array.sorted { (obj1, obj2) -> Bool in
    if let date1 = obj1["dateString"], let date2 = obj2["dateString"] {
        return date1 < date2
    }
    return false
}

假设给定了一个表示日期的字符串数组:

let array: [String] = ["2018-03-06", "2018-03-05"]

// Transform the given array of strings into an array of Date objects
var dates: [Date] = []
for dateString in array {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    if let date = dateFormatter.date(from: dateString) {
        dates.append(date)
    }
}
// Now apply any kind of sort you like
// e.g. ascending
dates.sort(by: { lhs, rhs in
    return lhs < rhs
})
// or descending
dates.sort(by: { lhs, rhs in
    return lhs > rhs
})

您可以将日期字符串转换为日期格式,然后与每个进行比较以找到排序的数组。

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-dd-MM"// yyyy-MM-dd"

var convertedArray: [Date] = []

var dateArray = ["2018-03-06", "2018-03-05"]
for dat in dateArray {
    let date = dateFormatter.date(from: dat)
    if let date = date {
        convertedArray.append(date)
    }
}

let ready = convertedArray.sorted(by: { [=10=].compare() == .orderedAscending })
// For Descending use .orderedDescending 
print(ready) //[2018-05-02 18:30:00 +0000, 2018-06-02 18:30:00 +0000]

var newList = [String]()
for date in ready {
    let dateformatter =  DateFormatter()
    dateformatter.dateFormat = "dd-MM-yyyy"
    let convertDate = dateformatter.string(from: date)
    newList.append(convertDate)
}
print(newList) //["03-05-2018", "03-06-2018"]