我的应用程序显示消息列表,每个消息都有一个创建日期. 
  
 
我不想只显示日期,而是根据创建日期过去的时间显示不同的格式.
例如,这是我从日期创建日期字符串的方式:
NSDate *date = someMessage.creationDate;
NSTimeInterval timePassed = [[NSDate date] timeIntervalSinceDate:date];
if (timePassed < 60 ) { // less then one minute
  return @"Now"
} else if (timePassed < 3600) { // less then one hour
  NSInteger minutes = (NSInteger) floor(timePassed / 60.0);
  return [Nsstring stringWithFormat:@"%d minutes ago",minutes];
} 
 所以现在我想添加以下案例:
else if ("timePassed < 24 hours ago and within the same calendar day")
   // do something
} else if ("timePassed > 24 hours,or within prevIoUs calendar day") {
   // do something else
} 
 但不知道该怎么做,任何帮助将不胜感激
解决方法
 这是NSDate上的一个简单类别,它添加了有用的日期比较方法: 
  
  
 
        #ifndef SecondsPerDay
  #define SecondsPerDay 86400
#endif
@interface NSDate (Additions)
/**
 *  This method returns the number of days between this date and the given date.
 */
- (NSUInteger)daysBetween:(NSDate *)date;
/**
 *  This method compares the dates without time components.
 */
- (NSComparisonResult)timelessCompare:(NSDate *)date;
/*  
 * This method returns a new date with the time set to 12:00 AM midnight local time.
 */
- (NSDate *)dateWithoutTimeComponents;
@end
@implementation NSDate (Additions)
- (NSUInteger)daysBetween:(NSDate *)date
{
  NSDate *dt1 = [self dateWithoutTimeComponents];
  NSDate *dt2 = [date dateWithoutTimeComponents];
  return ABS([dt1 timeIntervalSinceDate:dt2] / SecondsPerDay);
}
- (NSComparisonResult)timelessCompare:(NSDate *)date
{
  NSDate *dt1 = [self dateWithoutTimeComponents];
  NSDate *dt2 = [date dateWithoutTimeComponents];
  return [dt1 compare:dt2];
}
- (NSDate *)dateWithoutTimeComponents
{
  NSCalendar *calendar = [NSCalendar currentCalendar];
  NSDateComponents *components = [calendar components:NSYearCalendarUnit  |
                                                      NSMonthCalendarUnit |
                                                      NSDayCalendarUnit
                                             fromDate:self];
  return [calendar dateFromComponents:components];
}
@end 
 示例使用:
NSDate *currentDate = [NSDate date]; NSDate *distantPastDate = [NSDate distantPast]; NSComparisonResult *result = [currentDate timelessCompare:distantPastDate]; // result will equal NSOrderedDescending
需要及时了解更详细的差异吗?
你需要知道两个日期到第二个日期之间的区别吗?使用timeIntervalSinceDate:这是NSDate的标准配置.