Reputation: 1435
I have a custom calendar setup using a UICollectionView and I have an array that hold dates through 30 days. What I am trying to do is find out if a value is between the current date and 7 days before it. If it is I need it to do something. I cannot figure out what I am doing wrong. Here is what I have so far:
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"MM-dd-yy"];
NSdate *date = [NSDate date];
NSDate *newCurrentDate = [date dateByAddingTimeInterval:+14*24*60*60];
NSDate *sevenDaysBeforeCurrent = [date dateByAddingTimeInterval:-7*24*60*60];
if([[df stringFromDate:[days objectAtIndex:indexPath.item]] compare:[df stringFromDate:newCurrentDate]] == NSOrderedAscending && [[df stringFromDate:[days objectAtIndex:indexPath.item]] compare:[df stringFromDate:sevenDaysBeforeCurrent]] == NSOrderedDescending )
{
UIImage *buttonImage = [UIImage imageNamed:@"dates.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
}
What it does is change the image of every date before the newCurrentDate instead of just the previous 7. Can anyone see what I am doing wrong?
Heres the initialization of the array:
myDays = [[NSMutableArray alloc] init];
NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
NSDate *today = [NSDate date];
date = [NSDate date];
for (int i = 0; i < 31; i++)
{
NSDateComponents *comps = [[NSDateComponents alloc]init];
[comps setDay:i];
[myDays addObject:[cal dateByAddingComponents:comps toDate:today options:0]];
}
Upvotes: 1
Views: 1089
Reputation: 114
You don't need to be using the dateFormatter.
if([dateInQuestion compare:newCurrentDate] == NSOrderedAscending && [dateInQuestion compare:sevenDaysBeforeCurrent] == NSOrderedDescending){
// do something
}
Upvotes: 5
Reputation: 6036
Try something along these lines:
NSDate *currentDate = [NSDate date];
NSDate *dateSevenDaysPrior = [currentDate dateByAddingTimeInterval:-(7 * 24 * 60 * 60)];
NSDate *someDate = [currentDate dateByAddingTimeInterval:-(3 * 24 * 60 * 60)]; // adjust as you like
if (([dateSevenDaysPrior compare:someDate] != NSOrderedDescending) &&
([someDate compare:currentDate] != NSOrderedDescending))
{
NSLog(@"date is in range");
}
else
{
NSLog(@"date is not in range");
}
This assumes that what you're providing (what someDate
is standing for in this example) really is an instance of NSDate.
Upvotes: 1