Nata Mio Nata Mio - 5 months ago 20
Swift Question

Sort Objects in Array by date

I have an

array
containing object called
HistoryObject
and it has properties which is "date", "name", etc.

I am sorting the
array
as the following :

let sortedArray = HistoryArray.sort({ $0.date.compare($1.date) == NSComparisonResult.OrderedDescending})


which is supposed to sort the date from newer to oldest. For example:


Jun 30, 2016

Jun 29, 2016`


etc..

But when my
array
contains
Jul 2, 2016
the sorted
array
becomes :


Jun 30, 2016

Jun 29, 2016

Jul 2, 2016


Where
Jul 2, 2016
should be on top after sorting, now it's on the bottom? How can I fix this problem?

Thanks in advance!

Answer

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)