你怎麼樣纔算今天在00:00,然後在明天00:00,然後在謂語比較日期的(> =和<)。因此,所有日期對象都必須在這兩個日期之內被歸類爲「今日」。這要求您僅在最初計算兩個日期,而不管數組中有多少個日期對象。
// Setup
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
// Get todays year month and day, ignoring the time
NSDateComponents *comp = [cal components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:now];
// Components to add 1 day
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
oneDay.day = 1;
// From date & To date
NSDate *fromDate = [cal dateFromComponents:comp]; // Today at midnight
NSDate *toDate = [cal dateByAddingComponents:oneDay toDate:fromDate options:0]; // Tomorrow at midnight
// Cleanup
[oneDay release]
// Filter Mutable Array to Today
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dueDate >= %@ && dueDate < %@", fromDate, toDate];
NSArray *filteredArray = [allObjectsArray filteredArrayUsingPredicate:predicate];
// Job Done!
這種方法可行,但它需要大量的日期處理和每個項目的計算。所以如果有幾百個項目(或更多),那麼處理時間會開始累加。 –
最重要的是,需要注意以下幾項: http://www.mikeabdullah.net/NSCalendar_currentCalendar.html –