I'm using DBAccess
framework and one of my model store the date when the record what created simply by using [NSDate date]
and store to DB using DBAccess
framework. Now when I am trying to retrieve using query it fails. I want to retrieve only last 7 days records and have written a query like
DBResultSet* result = [[[weightModel query] whereWithFormat:@"savedAt >= %@ AND savedAt <= %@", beforeDate, beforeDate] fetch];
Where beforeDate is NSDate
is
-(NSDate*)getDateFor:(int)daysBack {
NSDate* date = [NSDate date];
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = -daysBack;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* beforeDate = [calendar dateByAddingComponents:comps toDate:date options:0];
return beforeDate;
}
Anyone know how can i get NSDate
for last 7 days records?
However, i have confirmed these records exists using
weightModel* weightRecord = [[[weightModel query] fetch] objectAtIndex:i];
[dates weightRecord.savedAt];
and printed it.
Initially I answered your question saying there doesn't seem to be an issue with the way you were producing and querying for dates. However, one small subtlety escaped me and that was, that you were querying for dates >= && <= where the parameter was the same date value.
Given that an NSDate
object has an accuracy greater than 1 second would mean that your record would have had to have existed at the exact same millisecond (*citation required, unsure of actual accuracy) 7 days ago. Which is unlikely to return any results.
What you need to do is create a date function that returns the Beginning of a day and the end of a day.
OR, you could use the SQLite
datetime
functions to do this for you. But I would suggest keeping it within obj-c.
Thanks Adrian