本文介绍了替换字符串列表中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将我的 list 与对象按属性 time 排序,它是 String 而不是 date.

I've sorted my list with objects by propertie time which is String not 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 之后:

and after invoking 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 仅当它是 AM12 时 开头?

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 ?

提前致谢!

推荐答案

我认为这就是您要寻找的.始终以这种方式比较日期!

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)
    }
}

这篇关于替换字符串列表中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 00:47