Reputation: 2025
I am trying to sort dates in ascending order. I am able to solve the date in the format "MM/dd/yyyy"
but when changed to this format "dd mmm yyyy"
I get an error.
This works
var dateArray = [Date]()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
dateArray.append(dateFormatter.date(from: "09/04/2016")!)
dateArray.append(dateFormatter.date(from: "01/01/2000")!)
dateArray.append(dateFormatter.date(from: "12/12/1903")!)
dateArray.append(dateFormatter.date(from: "04/23/2222")!)
dateArray.append(dateFormatter.date(from: "08/06/1957")!)
dateArray.append(dateFormatter.date(from: "11/11/1911")!)
dateArray.append(dateFormatter.date(from: "02/05/1961")!)
dateArray.sort { (date1, date2) -> Bool in
return date1.compare(date2) == ComparisonResult.orderedAscending
}
for date in dateArray {
print(dateFormatter.string(from: date))
}
but this does not
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd mmm yyyy"
dateArray.append(dateFormatter.date(from:"01 Mar 2017")!)
dateArray.append(dateFormatter.date(from: "03 Feb 2017")!)
dateArray.append(dateFormatter.date(from: "15 Jan 1998")!)
dateArray.sort { (date1, date2) -> Bool in
return date1.compare(date2) == ComparisonResult.orderedAscending
}
for date in dateArray {
print(dateFormatter.string(from: date))
}
Upvotes: 1
Views: 436
Reputation: 1961
var dateArray = [Date]()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
dateArray.append(dateFormatter.date(from:"01 Mar 2017")!)
dateArray.append(dateFormatter.date(from: "03 Feb 2017")!)
dateArray.append(dateFormatter.date(from: "15 Jan 1998")!)
dateArray.sort { (date1, date2) -> Bool in
return date1.compare(date2) == ComparisonResult.orderedAscending
}
for date in dateArray {
print(dateFormatter.string(from: date))
}
Upvotes: 0
Reputation: 2632
Use "MMM" instead of "mmm"
MMM
is The shorthand name of the month m, mm
are for minutes
Please check this site https://nsdateformatter.com will help to understance about NSDateFormatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
dateArray.append(dateFormatter.date(from:"01 Mar 2017")!)
dateArray.append(dateFormatter.date(from: "03 Feb 2017")!)
dateArray.append(dateFormatter.date(from: "15 Jan 1998")!)
dateArray.sort { (date1, date2) -> Bool in
return date1.compare(date2) == ComparisonResult.orderedAscending
}
for date in dateArray {
print(dateFormatter.string(from: date))
}
Upvotes: 3
Reputation: 100503
You need MMM
isntead of mmm
dateFormatter.dateFormat = "dd MMM yyyy"
Upvotes: 1