How to filter Realm objects through the NSDate property

I am trying to filter out Realm objects to find those with createdAt dates less than a year ago:

  let datex = NSCalendar.currentCalendar().startOfDayForDate(NSDate()).dateByAddingTimeInterval(-1*365*24*60*60) let list = RealmDB.objects(TaskList).filter("createdAt <= '\(datex)'") 

I get the following error:

The expected date object for the "createdAt" property on the "TaskList" object, but received: "2015-03-19 21:00:00 +0000"

How to fix it? It also looks like the date and time are set to the time zone. How can I make sure the date is really the end of the day?

+5
source share
1 answer

The immediate problem is that you are using Swift string interpolation to construct your predicate, and not to replace the NSPredicate argument. This causes your predicate to be something like:

 createdAt <= '2015-03-19 07:00:00 +0000' 

This is an attempt to compare createdAt , a date with a string literal. Using an NSPredicate replacement looks like this:

 let list = RealmDB.objects(TaskList).filter("createdAt <= %@", datex) 

Note that the way you calculate the date is incorrect in the face of leap days, leap seconds, breaks due to daylight saving time, etc. You should use NSCalendar methods to math dates, and not do math with magic constants:

 let calendar = NSCalender.currentCalendar() let datex = calendar.dateByAddingUnit(.Year, value: -1, toDate: calendar.startOfDayForDate(NSDate()), options: [.MatchFirst]) 

Keep in mind that NSDate is a single point in time, regardless of any time zone. The default NSDate used when calling -[NSDate description] occurs with date formatting in UTC. If you want to format the date in a string using a different time zone, you can use NSDateFormatter and explicitly specify the time zone.

+5
source

Source: https://habr.com/ru/post/1245352/


All Articles