1

I have an array, workoutData, of string dates in the format EEEE, d MMM, yyyy so the dates are saved as Tuesday, 30 Apr, 2019, Thursday, 25 Apr, 2019 and Saturday, 27 Apr, 2019 etc. I have tried using the sorted(by:) method below however this orders the dates alphabetically.

let orderedArray = self.workoutData.sorted(by: { $0.compare($1) == .orderedDescending})

How can I order this array in a descending order by date? I would like to keep the individual dates as strings and I am using these to populate a tableView.

Excuse the lack of experience. Thanks

gcpreston
  • 135
  • 1
  • 12
  • Use a `(NS)DateFormatter` to interpret the Date String as Date and then sort. – Larme May 01 '19 at 10:31
  • https://stackoverflow.com/questions/38168594/sort-objects-in-array-by-date – Sumit singh May 01 '19 at 10:44
  • FYI - you should convert those strings to `Date` once when loading the data. Don't keep the strings around. This will make all future processing much more efficient. This includes sorting and later showing those dates to users in the proper format for their locale. – rmaddy May 01 '19 at 16:05

1 Answers1

4

First you need to create DateFormatter with certain Locale and DateFormat which you need

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEEE, d MMM, yyyy"

Then you can sort your String array like this: You create Date from String using DateFormatter and then you just sort two Date values

let ordered = workoutData.sorted { string1, string2 in
    guard let date1 = formatter.date(from: string1), let date2 = formatter.date(from: string2) else { return false }
    return date1 < date2
}
Robert Dresler
  • 10,580
  • 2
  • 22
  • 40