Sort Objects in Array by date
For Swift 3
var testArray = ["25 Jun, 2016", "30 Jun, 2016", "28 Jun, 2016", "2 Jul, 2016"]
var convertedArray: [Date] = []
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
for dat in testArray {
var date = dateFormatter.date(from: dat)
convertedArray.append(date!)
}
//Approach : 1
convertedArray.sort(){$0 < $1}
//Approach : 2
convertedArray.sorted(by: {$0.timeIntervalSince1970 < $1.timeIntervalSince1970})
print(convertedArray)
Avoiding extra variable of convertedArray
Using Swift 4 & Swift 3
let testArray = ["25 Jun, 2016", "30 Jun, 2016", "28 Jun, 2016", "2 Jul, 2016"]
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MM, yyyy"// yyyy-MM-dd"
var ready = convertedArray.sorted(by: { dateFormatter.date(from:$0).compare(dateFormatter.date(from:$1)) == .orderedDescending })
print(ready)
Using Swift 4 & Swift 3
let testArray = ["25 Jun, 2016", "30 Jun, 2016", "28 Jun, 2016", "2 Jul, 2016"]
var convertedArray: [Date] = []
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MM, yyyy"// yyyy-MM-dd"
for dat in testArray {
let date = dateFormatter.date(from: dat)
if let date = date {
convertedArray.append(date)
}
}
var ready = convertedArray.sorted(by: { $0.compare($1) == .orderedDescending })
print(ready)
Using Swift 2
For example you have the array with dates and another 1 array, where you will save the converted dates:
var testArray = ["25 Jun, 2016", "30 Jun, 2016", "28 Jun, 2016", "2 Jul, 2016"]
var convertedArray: [NSDate] = []
After that we convert the dates:
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MM, yyyy"// yyyy-MM-dd"
for dat in testArray {
var date = dateFormatter.dateFromString(dat)
convertedArray.append(date!)
}
And the result:
var ready = convertedArray.sort({ $0.compare($1) == .OrderedDescending })
print(ready)