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

标签 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
}

但不知道怎么做,任何帮助将不胜感激

最佳答案

这是 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 的标准。

关于ios - 检测两个日期是否在同一日历日内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21364747/

相关文章:

ios - 如何多次显示 admob 插页式广告?

objective-c - 按下自定义单元格文本标签时,didSelectRowAt Index 不会触发

iphone - 如何从 iPhone 邮件和 safari 获取 ppt 文件?

objective-c - AFNetworking + 队列 + 取消操作 + 垃圾文件

objective-c - NSArray 和快速枚举,总是按索引顺序进行?

ios - 对 HTTPS 域的 alamofire 请求与对 HTTP 域的请求有什么不同吗?

iphone - 替换特殊字符的问题

ios - iPhone 6 Plus 无法识别过滤器 : blur() Css

iphone - 将两个 SQLite 存储合并为一个

ios - UITableViewCell 强引用循环,但未被 Instruments 中的 Leaks 发现