I have an array of date as 2017-07-06,2017-06-07,2017-07-07. I want to sort these dates in ascending order. So 2017-06-07 will come first. But it is not happening at all. I am using below code for this:
func sortDates(array:NSMutableArray)->[String] {
var strArray:[String] = []
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"// yyyy-MM-dd"
var convertedArray: [Date] = []
for dat in array {
let date = dateFormatter.date(from: dat as! String)
convertedArray.append(date!)
}
let arrDates = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
for value in arrDates {
let formatter = DateFormatter()
// initially set the format based on your datepicker date
formatter.dateFormat = "yyyy-MM-dd"
let myString = formatter.string(from: value)
// convert your string to date
let yourDate = formatter.date(from: myString)
if yourDate != nil {
//then again set the date format whhich type of output you need
formatter.dateFormat = "yyyy-MM-dd"
// again convert your date to string
let myStringafd = formatter.string(from: yourDate!)
strArray.append(myStringafd)
}
}
return strArray
}
Please guide me where I am doing wrong ?
yyyy-MM-dd, not withmmThe lowercase one is for minutes (see the doc unicode.org/reports/tr35/tr35-31/…).$0 < $1