3

I am trying to retrieve a DATETIME field called TIMESTAMP from an SQLite DB with the following code:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
var d1: NSDate  = NSDate()
if getData.dictLocations["TIMESTAMP"] != nil {    
    d1 = dateFormatter.dateFromString(getData.dictLocationsNames["TIMESTAMP"]!)!
    } else {
    dateCreatedLabel.text = "FAILED"
} 

The problem seems to stem from the fact that there are only two options for getData:

getData.dictLocation which is <String, Double> or
getData.dictLocationNames which is <String, String>

So how do I pull a date? Needless to say the sample code always displays, "FAILED".

Any ideas? I am using FMDB.

This replaces a similar question I asked earlier today, now deleted, that was too broad.

Edward Hasted
  • 3,201
  • 8
  • 30
  • 48
  • Use CoreData? That will return an actual date and doesn't require a third party framework. – Fogmeister Jul 04 '15 at 19:13
  • You need to simplify this further. Construct a [MCVE](http://stackoverflow.com/help/mcve), the simplest possible example of the problem you're experiencing. – Rob Jul 04 '15 at 20:14
  • Can you point me at an example? I believe you implicitly but don't appreciate how I translate this into code. – Edward Hasted Jul 04 '15 at 20:16
  • For what it's worth, in the future, I might recommend that you come up with examples that don't require any knowledge of your app's internal workings. Here you are referring to some opaque `getData` structure, updating `UILabel` controls which are not relevant, and don't even show us the FMDB calls you made. Bottom line, distill the question to it's absolute simplest form, removing as much of your code as possible. But hopefully we've pointed you in the right direction. Good luck! – Rob Jul 04 '15 at 21:13

1 Answers1

1

When you pass NSDate object as parameter to executeQuery or executeUpdate in FMDB, it does the necessary conversion for you. You don't have to (and shouldn't) use NSDateFormatter at all. Let FMDB handle that for you.

For example:

if !db.executeUpdate("create table foo (bar text, transactionTimestamp text)", withArgumentsInArray: nil) {
    println(db.lastErrorMessage())
}

if !db.executeUpdate("insert into foo (bar, transactionTimestamp) values (?, ?)",  withArgumentsInArray: ["baz", NSDate()]) {
    println(db.lastErrorMessage())
}

if let rs = db.executeQuery("select bar, transactionTimestamp from foo", withArgumentsInArray: nil) {
    while rs.next() {
        let bar       = rs.stringForColumn("bar")
        let timestamp = rs.dateForColumn("transactionTimestamp")

        println("bar = \(bar); timestamp = \(timestamp)")
    }
    rs.close()
} else {
    println(db.lastErrorMessage())
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044