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

3
  • Use a (NS)DateFormatter to interpret the Date String as Date and then sort. Commented May 1, 2019 at 10:31
  • stackoverflow.com/questions/38168594/… Commented May 1, 2019 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. Commented May 1, 2019 at 16:05

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.