问题
I've sorted my list with objects by propertie time which is String not date.
The sample output before sorting :
07:05:10 AM
07:05:01 AM
07:04:49 AM
07:04:44 AM
06:53:58 AM
06:53:47 AM
01:03:21 AM
12:03:21 AM
and after invoking instrudtion :
self.myList = self.myList.sorted { $0.mytime < $1.mytime }
going to looks like this :
01:03:21 AM
06:53:47 AM
06:53:58 AM
07:04:44 AM
07:04:49 AM
07:05:01 AM
07:05:10 AM
12:03:21 AM
Could I replace 12:03:21 AM to 00:03:21 AM only when it is AM and 12 at the beginning ?
Or there is different way to do this ?
Thanks in advance!
回答1:
I think this is what you are looking for. Always compare dates in this manner!
override func viewDidLoad() {
super.viewDidLoad()
var arrayOfDates = ["07:05:10 AM",
"07:05:01 AM",
"07:04:49 AM",
"07:04:44 AM",
"06:53:58 AM",
"06:53:47 AM",
"01:03:21 AM",
"12:03:21 AM"]
// This will throw an error if any of your dates are
// misformatted, so handle that appropriately.
arrayOfDates.sort() { $0.toDate()!.compare($1.toDate()!) == ComparisonResult.orderedDescending }
print("Descending: \(arrayOfDates)")
arrayOfDates.sort() { $0.toDate()!.compare($1.toDate()!) == ComparisonResult.orderedAscending }
print("Ascending: \(arrayOfDates)")
}
extension String {
func toDate() -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm:ss a"
if let date = formatter.date(from: self) {
return date
} else {
return nil
}
}
//If you need a string version of the date you can use this as well
extension Date {
func toString() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm:ss a"
return formatter.string(from: self)
}
}
来源:https://stackoverflow.com/questions/42999852/replace-characters-in-list-of-strings