我的应用显示消息列表,每条消息都有一个创建日期。
我不想只显示日期,而是根据从创建日期过去的时间显示不同的格式。
例如,这是我从日期创建日期字符串的方式:
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/