我已根据list
而不是time
的属性String
对date
对象进行了排序。
排序前的样本输出:
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
并在调用instrudtion之后:
self.myList = self.myList.sorted { $0.mytime < $1.mytime }
看起来像这样:
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
我是否可以将12:03:21 AM
替换为00:03:21 AM
仅在AM
和12
开头时?
或者有不同的方法可以做到这一点?
提前致谢!
答案 0 :(得分:1)
我认为这就是你要找的东西。总是以这种方式比较日期!
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)
}
}