How to Sort an Array of NSDictionary using DateTime key (Swift 4)?

后端 未结 1 1354
情书的邮戳
情书的邮戳 2021-01-28 17:29

I have an NSArray of NSDictionary

let Array = (
{ name = \"Auni\";
  age = \"24\";
  transactionTime = \"01-02-2011 12:32:39\" },
{ name = \"Atiqah\";
  age = \"         


        
相关标签:
1条回答
  • 2021-01-28 18:09

    You do not need to convert into Date object, dateStrings direct comparison will also work.

    array.sort { (dict1, dict2) -> Bool in
    
        /// Considering "transactionTime" key always exists.
        let transactionTime1 = dict1["transactionTime"]!
        let transactionTime2 = dict2["transactionTime"]!
    
        /// Sort in descending order
        return transactionTime1 > transactionTime2
    }
    

    In case you need some calculation on date objects then You can also convert the string into date objects at run time like below example:

    let df = DateFormatter()
    df.dateFormat = "dd-MM-yyyy HH:mm:ss"
    array.sort { (dict1, dict2) -> Bool in
    
        /// Considering "transactionTime" key always exists.
        let transactionTime1 = dict1["transactionTime"]!
        let transactionTime2 = dict2["transactionTime"]!
    
        let date1 = df.date(from: transactionTime1)!
        let date2 = df.date(from: transactionTime2)!
    
        /// Sort in descending order
        return date1 > date2
    }
    
    print(array)
    

    Output

    [["transactionTime": "04-02-2020 18:32:21", "name": "Aida", "age": "22"], ["transactionTime": "02-02-2013 10:32:41", "name": "Atiqah", "age": "23"], ["transactionTime": "01-02-2011 12:32:39", "name": "Auni", "age": "24"]]

    0 讨论(0)
提交回复
热议问题