iphone - 比较今天或昨天的 NSDate

标签 iphone uitableview nsdate

好吧,我想这个问题已经被问过一千次了,但由于某种原因,答案并没有真正起作用或有其他问题,......

无论如何,这就是我的“工作”:

    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];
}

现在解决问题:

这似乎只是日期比较的大量代码,有更简单的方法吗?

最重要的问题是所有对象的释放。正如您可能已经猜到的,我在 UITableViewController 中使用了它。我的代码中也有这些行:

//[calendar release];
//[currentDate release];
//[dateToday release];
//[dateYesterday release];
//[todayString release];
//[yesterdayString release];
//[refDateString release];

问题是,一旦我取消注释其中一行,我的应用程序就会崩溃,我不知道为什么?!希望有人能在这里启发我。

非常感谢。

最佳答案

最简单的方法就是比较日期的描述:

// Your dates:
NSDate * today = [NSDate date];
NSDate * yesterday = [NSDate dateWithTimeIntervalSinceNow:-86400]; //86400 is the seconds in a day
NSDate * refDate; // your reference date

// 10 first characters of description is the calendar date:
NSString * todayString = [[today description] substringToIndex:10];
NSString * yesterdayString = [[yesterday description] substringToIndex:10];
NSString * refDateString = [[refDate description] substringToIndex:10];

if ([refDateString isEqualToString:todayString]) 
{
    cell.title.text =  @"Today";
} else if ([refDateString isEqualToString:yesterdayString]) 
{
    cell.title.text =  @"Yesterday";
} else 
{
    cell.title.text =  refDateString;
}

如果您想更改日期字符串的格式,可以使用 descriptionWithLocale: 代替。

关于iphone - 比较今天或昨天的 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2893835/

相关文章:

iphone - 如何检测Game Center支持?

ios - Apple TV 的闹钟和电话

ios - 当用户点击带有 `UITableView` 的单元格时,在 `UITextField` 上添加自动完成列表/表格

cocoa - strtotime -> NSDate

iphone - NSDateFormatter 返回不正确的字符串?

iphone - NSString stringWithFormat 混合以允许丢失格式编号参数

iphone - 如何使用 Interface Builder 添加导航 Controller ?

ios - EXC_BAD_access code=1 地址 0x NSURLConnection JSON

swift - 修复 UITableViewController 的 UINavigationBar 下面的 UILabel 位置

iphone - NSString 到 NSDate 转换问题