简体   繁体   中英

Sorting of array of dictionary with date Swift 3

I have an array called myArray in which dictionaries are added I want that dictionary to be sorted by time which is a key in dictionary. And that time is in String. The date format of time is "yyyy/MM/dd HH:mm:ss"

I tried with below code solution but gives a warning of "Cast from 'String?' to unrelated type 'Date' always fails".

let sortedArray = self.myArray.sorted{ ($0["Time"] as? Date)! > ($1["Time"] as? Date)! }
print(sortedArray)

If anyone can help me out, Thank You.

You don't need to convert to date time for this sort. The international format (yyyy/MM/dd HH:mm:ss) you're using provides the right sorting order as a string.

You have to convert string into date using this code:

 let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
    let date = dateFormatter.date(from: "2017/04/22 00:00:00") ?? Date()

So, use this:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"

    let sortedArray = self.myArray.sorted{[dateFormatter] one, two in
     return dateFormatter.date(from:one["Time"] )! > dateFormatter.date(from: two["Time"] )! }
//Sort any dictionary with string dates using any date format
var incisions = [["initials": "B.B. ", "date": "12/18/17 09:39 AM", "patientID": "snowball"], ["patientID": "snowball", "date": "01/03/18 04:03 PM", "initials": "C.J."], ["initials": "B.B. ", "date": "01/04/18 09:47 AM", "patientID": "snowball"]]

func sortArrayDictDescending(dict: [Dictionary<String, String>], dateFormat: String) -> [Dictionary<String, String>] {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = dateFormat
                return dict.sorted{[dateFormatter] one, two in
                    return dateFormatter.date(from: one["date"]! )! > dateFormatter.date(from: two["date"]! )! }
            }

   //use:
let sortedArray = sortArrayDictDescending(dict: incisions, dateFormat: "MM/dd/yy a")

for i in sortedArray {
 print("incisions \(i["date"]!)")
}

//output:
incisions 01/04/18 09:47 AM
incisions 01/03/18 04:03 PM
incisions 12/18/17 09:39 AM

simple code for sort an array of dictionary with date

let formatter = NSDateFormatter()
formatter.dateFormat = "MMM d, yyyy hh:mm a"
formatter.locale = NSLocale(localeIdentifier: "en_US")

let sorted = displayArray.sort {
    formatter.dateFromString($0["fullfireDate"] as! String)?.compare(formatter.dateFromString($1["fullfireDate"] as! String)!) != .OrderedAscending
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM