Search code examples
iphoneobjective-cnsdatensdateformatternstimeinterval

NSTimeInterval seems to be wrong for last day of the given month- iOS


In my local database, I have a list of NSTimeInterval values saved. I have to find out and fetch all records available in a given Month. The only problem is in fetching records for last day of the given month seems to be unavailable.

Lets say given month is December so I have to fetch all the records from 1st Dec to 31st Dec (Till 11:59PM)

I am using following implementation:

[self.dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *startDate = [self.dateFormatter dateFromString:@"1-12-2012"];
NSDate *endDate = [self.dateFormatter dateFromString:@"31-12-2012"];

NSTimeInterval startDateTimeInterval = [startDate timeIntervalSince1970];
NSTimeInterval endDateTimeInterval = [endDate timeIntervalSince1970];

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"(mdate >= %f) AND (mdate <= %f)",startDateTimeInterval,endDateTimeInterval]];

I have noticed that endDateTimeInterval double value is pretty less as compared to saved value in the database for 31st (9AM). But howz it possible, I am expecting my endDateTime should be till 31st Dec 11:59 PM.

Please provide your inputs on this issue.


Solution

  • The NSDate objects you are creating implicitly have a time of 00:00. So the predicate search will not include the last day from time 00:01 to 23:59. The easiest change is to set the end date to the next day (first of next month) and change the predicate to a less than, instead of less than or equal.

    [self.dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *startDate = [self.dateFormatter dateFromString:@"1-12-2012"]; // start of range, inclusive
    NSDate *endDate = [self.dateFormatter dateFromString:@"1-1-2013"]; // end of range, exclusive
    ...        
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"(mdate >= %f) AND (mdate < %f)",startDateTimeInterval,endDateTimeInterval]];