I have an array of object with dateString
(of creation) as parametere. I wanna sort
the array of objects based on timestamp
(of creation).
For example,
array = ["dateString":"2018-03-06", "dateString":"2018-03-05"]
I have an array of object with dateString
(of creation) as parametere. I wanna sort
the array of objects based on timestamp
(of creation).
For example,
array = ["dateString":"2018-03-06", "dateString":"2018-03-05"]
You can convert date string to date formate then compare with each to find sorted array.
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"]
Considering your array has the following format:
let array: [[String: String]] = [
["dateString":"2018-03-06"],
["dateString":"2018-03-05"]
]
You should use sorted
method to get what you need:
let sortedArray = array.sorted { (obj1, obj2) -> Bool in
if let date1 = obj1["dateString"], let date2 = obj2["dateString"] {
return date1 < date2
}
return false
}
Assuming you are given an array of strings representing dates:
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
})