我在网上找到以下代码来比较两个日期(日历日期和另一个日期)我想要帮助的是修改此代码,以便将日历日期与日期事件的日期进行比较这里是NSArray(json文件)中每个事件的关键。另外我以后如何在NSPredicate中使用它,以便我可以加载至少有超过1天的组件事件(两个日期之间的差异)至少1天当用户点击它时,让UIButton调用未来事件,应该加载所有未来事件。我非常感谢任何帮助和代码示例,因为我对目标C和Xcode非常新。感谢。
@implementation HomeViewController {
NSArray *_events;
}
- (BOOL)isSameDay:(NSDate*)date
{
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate *currDate = [NSDate date];
//date = [_events objectAtIndex:date];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:currDate];
NSDateComponents *components = [calendar components:unitFlags
fromDate:currDate
toDate:date
options:0];
NSLog(@"Days between dates: %@", components);
return [comp1 day] == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year] == [comp2 year];
}
答案 0 :(得分:0)
要获取从现在开始的日期剩余天数,您可以使用以下方法:
-(long)daysRemaining:(NSDate*) date
{
NSDate *now = [NSDate date];
NSTimeInterval dateDiff = [date timeIntervalSinceNow] - [now timeIntervalSinceNow];
CGFloat numberOfDaysRemaining = (dateDiff/(60*60*24));
return ceil(numberOfDaysRemaining);
}
所以你可以打电话来获得这样的剩余天数:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *dateToCompare = [dateFormatter dateFromString: @"2014-02-08"];
long numberDays = [self daysRemaining:dateToCompare];
对于这种情况,结果是 2 天。请注意,否定结果表示已通过 n 天。
过滤数组(剩余2天事件)制作副本:
NSArray* dates = [[NSArray alloc] initWithObjects:
[dateFormatter dateFromString: @"2014-02-08"],
[dateFormatter dateFromString: @"2014-02-05"],
[dateFormatter dateFromString: @"2014-02-10"],
[dateFormatter dateFromString: @"2014-02-08"], nil];
NSArray *filteredArray = [dates filteredArrayUsingPredicate:
[NSPredicate predicateWithBlock:
^BOOL(id evaluatedObject, NSDictionary *bindings) {
long daysRemaining = [self daysRemaining:(NSDate*)evaluatedObject];
return daysRemaining == 2; // if someMethod returns YES, the object is kept
}
]];
过滤NSMutableArray:
[mutableArray filterUsingPredicate:[NSPredicate predicateWithBlock:
^BOOL(id evaluatedObject, NSDictionary *bindings) {
long daysRemaining = [self daysRemaining:(NSDate*)evaluatedObject];
return daysRemaining == 2; // if someMethod returns YES, the object is kept
}
]];
答案 1 :(得分:0)
[displayedEvents addObjectsFromArray:[_events filteredArrayUsingPredicate:
[NSPredicate predicateWithBlock:
^BOOL(Events * event, NSDictionary *bindings) {
[dateFormatter dateFromString: event.date];
long daysRemaining = [self daysRemaining: (NSDate*)event.date];
return daysRemaining > 1; // if someMethod returns YES, the object is kept
}
]]];