How to get documents filtering through NSDate property?

Hi , I am using Couchbase lite Mobile iOS. I added “createdDate” property to my document. I am assigning NSDate to “createdDate” property while creating the document.My problem is app crashes at “let result : CBLQueryEnumerator = try! cblQuery.run()”.Please review my code below which i am using to get documents from data base.

{
let predicate = NSPredicate(format: “documentType == %@ AND createdDate >= %@ AND createdDate <= %@”, argumentArray: [ModelNames.kUserModel,backDate,NSDate()])

    let query = try! CBLQueryBuilder(database: database, select: nil, wherePredicate: predicate, orderBy: nil)
    let cblQuery : CBLQuery  = query.createQueryWithContext(nil)
    
    cblQuery.descending = true
    
    let result : CBLQueryEnumerator = try! cblQuery.run()

}

The data base is giving result if i use the predicate like this(i.e when there is no NSDate property in predicate)

let predicate = NSPredicate(format: “documentType == %@”, argumentArray: [UserModel])

Thanks in Advance.

NSDate objects don’t have a JSON representation (JSON only knows about numbers, strings, booleans.) The dates in your documents are probably encoded as strings, usually in iSO-8601 format; if you want to compare them in a query you’ll need to provide an NSString in the same format. The CBLJSON class has utilities for converting dates to strings and vice versa.

2 Likes

Thank you @jens, its awesome. it is working great.