Sqlite - how to get a DATETIME field in Swift?
I am trying to get a DATETIME field called TIMESTAMP from 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 be related to 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 get the date? Needless to say, the sample code is always displayed, "FAILED".
Any ideas? I am using FMDB.
This replaces a similar question I asked earlier today, now deleted which was too broad.
source to share
When you pass an object NSDate
as a parameter to executeQuery
or executeUpdate
to FMDB, it does the required conversion for you. You don't need (and shouldn't) use it NSDateFormatter
at all. Let FMDB handle this.
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())
}
source to share