Reputation: 2330
In my application I have a list of NSDate instances. At one point I need to seperate the dates which are past to today ie [NSDate date]
(earlier to morning 12)
And I have used the logic like below. I feel there must be a better logic than this, so help me if there is better solution.
I pass the date instance as an argument to this method which will return a BOOL value corresponding to my requirement.
-(BOOL)checkIfPast:(NSDate *)date
{
NSDate *today=[NSDate date];
NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components1=[gregorianCalendar components:dateFlags fromDate:today];
NSDateComponents *components2=[gregorianCalendar components:dateFlags fromDate:date];
if (components2.day-components1.day<0) {
return YES;
}
else
{
return NO;
}
}
Upvotes: 1
Views: 276
Reputation: 81858
BOOL checkIfTodayOrFuture(NSDate *date)
{
NSDate *now = [NSDate date];
NSUInteger dateFlags = NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:dateFlags fromDate:now];
NSDate *midnight = [gregorianCalendar dateFromComponents:components];
return [date compare:midnight] == NSOrderedDescending;
}
If you have to make a lot of tests keep midnight
around and just do the compare:
on all of the dates.
Keep in mind that the result is not constant. For example, the user might change her timezone so the interval of "today" also changes.
Upvotes: 2
Reputation: 866
Create the Date for 12Am and make a Compare. The result says asc or dsc. I think asc is the One You want
Upvotes: 1