1

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))
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
King
  • 1,885
  • 3
  • 27
  • 84

3 Answers3

3

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))
}
Cruz
  • 2,602
  • 19
  • 29
1

You need MMM isntead of mmm

dateFormatter.dateFormat = "dd MMM yyyy"
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

Just change the format from lowercase "mmm" to uppercase "MMM", like this:

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))
}
Community
  • 1
  • 1
shbedev
  • 1,875
  • 17
  • 28