How to sort NSTableView Date Column?

I have a date column in a macOS NSTableView column in YYYY-MM-DD format and when using the code below the sort does not sort way I want. When sorting ascending. It has the year correct but the month is in reverse order. See image below. How can I fix this?

 func sortInvoices(invoiceColumn: String, ascending: Bool) {
         enum SortOrder {
            static let Date = "invoiceDateCreated"
            static let Number = "invoicenumber"
            static let Customer = "invoicecustomer"
            static let Status = "invoicestatus"
        }
        switch invoiceColumn {
        case SortOrder.Date:
           invoices.sort { (p1, p2) -> Bool in
               guard let id1 = p1.invoiceDateBilled, let id2 = p2.invoiceDateBilled else { return true }
               if ascending {
                   return id1 < id2
               } else {
                   return id2 < id1
               }
           }
Answered by BigEagle in 729660022

I changed the code to convert date to an integer and that worked for me as well changed to a different column.

let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "YYYYMMdd"
            dateFormatter.locale = Locale(identifier: "en_US_POSIX")
invoices.sort { (p1, p2) -> Bool in
                let p1Date: Int? = Int(dateFormatter.string(from: p1.invoiceDateCreated!))
                let p2Date: Int? =  Int(dateFormatter.string(from: p2.invoiceDateCreated!))
                guard let id1 = p1Date, let id2 = p2Date else { return true }
                if ascending {
                    return id1 < id2
                } else {
                    return id2 < id1
                }
            }
Accepted Answer

I changed the code to convert date to an integer and that worked for me as well changed to a different column.

let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "YYYYMMdd"
            dateFormatter.locale = Locale(identifier: "en_US_POSIX")
invoices.sort { (p1, p2) -> Bool in
                let p1Date: Int? = Int(dateFormatter.string(from: p1.invoiceDateCreated!))
                let p2Date: Int? =  Int(dateFormatter.string(from: p2.invoiceDateCreated!))
                guard let id1 = p1Date, let id2 = p2Date else { return true }
                if ascending {
                    return id1 < id2
                } else {
                    return id2 < id1
                }
            }
How to sort NSTableView Date Column?
 
 
Q