I am curious how to sort dates in form of Strings
in an array
. Most likely I would leave them in the same array
and sort
them the right way. Many attempts I have seen are with two. Also, they weren't the right time format so I want to know how to sort it with the "dd.MM.yyyy"
format. Most likely with only the last two numbers of the year. Is that possible?
Here is what I did. I want it to take the date in the struct to sort:
import UIKit
struct Post {
var title: String
var date: String
var user: String
}
var uploadTimes = [Post(title: "Hello", date: "02.10.2018", user: "Roman"),
Post(title: "Hi", date: "01.10.2018", user: "Roman"),
Post(title: "", date: "05.09.2018", user: "")]
uploadTimes = uploadTimes.map{ $0.components(separatedBy: ".").reversed().joined(separator: ".")}
print(uploadTimes)
//["2002.02.02", "2002.02.03", "2002.02.05", "2002.02.04"]
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [.withFullDate,]
let dates = uploadTimes.compactMap { isoFormatter.date(from: $0) }
print(dates)
let sortedDates = dates.sorted { $0 > $1 }
print(sortedDates)