Compare NSDate for Today or Yesterday
- by elementsense
Hi
Well I guess this has been asked a thousand times, but for some reason the answeres dont really work or had other problems,....
Anyway here is what I have "working" :
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
// set tomorrow (0: today, -1: yesterday)
[comps setDay:0];
NSDate *dateToday = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[comps setDay:-1];
NSDate *dateYesterday = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];
NSString *todayString = [self.dateFormatter stringFromDate:dateToday] ;
NSString *yesterdayString = [self.dateFormatter stringFromDate:dateYesterday] ;
NSString *refDateString = [self.dateFormatter stringFromDate:info.date];
if ([refDateString isEqualToString:todayString])
{
cell.title.text = @"Today";
} else if ([refDateString isEqualToString:yesterdayString])
{
cell.title.text = @"Yesterday";
} else
{
cell.title.text = [self.dateFormatter stringFromDate:info.date];
}
Now to the problem(s) :
That seems to be an awefull lot of code for just a date comparinson, is there an easier way ?
And the most important question is the release of all the objects. As might have guessed, I use this in a UITableViewController. I also have these lines in my code :
//[calendar release];
//[currentDate release];
//[dateToday release];
//[dateYesterday release];
//[todayString release];
//[yesterdayString release];
//[refDateString release];
The problem is that as soon that I uncomment one of these lines, my app crashes and I have no idea why ?! I hope someone can enlighten me here.
Thanks lot.