我有一个对象数组dateString
(创建)作为参数。我想sort
基于timestamp
(创造)的对象数组。
例如,
array = ["dateString":"2018-03-06", "dateString":"2018-03-05"]
答案 0 :(得分:1)
考虑到您的数组具有以下格式:
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
}
答案 1 :(得分:1)
假设给出了一个表示日期的字符串数组:
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
})
答案 2 :(得分:1)
您可以将日期字符串转换为日期格式,然后与每个字符串进行比较以查找已排序的数组。
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: { $0.compare($1) == .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"]