检测两个日期是否在同一日历日内

时间:2014-01-26 14:41:43

标签: ios iphone objective-c nsdate nscalendar

我的应用程序显示了一个消息列表,每个消息都有一个创建日期。

我不想只显示日期,而是根据创建日期过去的时间显示不同的格式。

例如,这是我从日期创建日期字符串的方式:

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
}

但不确定如何做,任何帮助将不胜感激

2 个答案:

答案 0 :(得分:7)

这是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

答案 1 :(得分:1)

您将要查看this answer

即:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:yourDate];

NSUInteger year = [components year];
NSUInteger dayOfYear = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:yourDate];

检查两个NSDates的day属性,然后您将知道它们是否在同一个calandar日。对于24小时或更少/更多,您可以使用一个日期并使用函数timeIntervalSinceDate:,看看是否多于/少于86400(一天中的数秒)。

编辑:更新为年复一年更具体的支票。