0

I have saved a few dates in my sqlite table and they are stored as strings. For example: Oct 4, 2018. How can I sort it so the newest is at the top? This is how I get the date:

func getData() {
    do {
        let wos = try self.database.prepare(self.woTable)
        for wo in wos {
            print("userId: \(wo[self.id]), date: \(wo[self.date])")

            if !mywos.contains("\(wo[self.date])") {
                mywos.append(workout[self.date])
                print(mywos)
                tableView.reloadData()
            }

        }
    } catch {
        print(error)
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Trinity
  • 15
  • 7
  • Before it's too late you need to change how you store your dates. Storing a date in that string format is about the worst way possible. If you must store it as a string, use a format such as "yyyyMMdd" since that is at least a sortable format. But a much better choice is to store the date as a number of seconds. Then it's simple to either sort or to create a `Date` instance without dealing for strings and formats. Once you do this, the task in this question becomes much simpler and much more efficient. – rmaddy Oct 06 '18 at 18:32
  • @rmaddy Ok! I will give that a try. Should I store it as a `Date` or `NSDate`? – Trinity Oct 06 '18 at 18:38
  • 1
    Neither. Store it as a number such as `someDate.timeIntervalSinceReferenceDate`. – rmaddy Oct 06 '18 at 19:03
  • @rmaddy Ok, thanks! – Trinity Oct 06 '18 at 19:04

1 Answers1

0

Whenever you fetch the data from sql lite database, fetch it in descending order of dates so it will store in the same order in your in memory collection like array.

Finally the data in collection will get bind in order.

Visit this link for order by clause: https://www.tutorialspoint.com/sqlite/sqlite_order_by.htm