Replace characters in List of strings

孤者浪人 提交于 2019-12-25 09:06:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!