返回x分钟前/x小时前/昨天/x天前/x个月前/x年前
- (NSString *)timeInfo {
return [NSDate timeInfoWithDate:self];
}
+ (NSString *)timeInfoWithDate:(NSDate *)date {
return [self timeInfoWithDateString:[self stringWithDate:date format:[self ymdHmsFormat]]];
}
+ (NSString *)timeInfoWithDateString:(NSString *)dateString {
NSDate *date = [self dateWithString:dateString format:[self ymdHmsFormat]];
NSDate *curDate = [NSDate date];
NSTimeInterval time = -[date timeIntervalSinceDate:curDate];
int month = (int)([curDate month] - [date month]);
int year = (int)([curDate year] - [date year]);
int day = (int)([curDate day] - [date day]);
NSTimeInterval retTime = 1.0;
if (time < 3600) { // 小于一小时
retTime = time / 60;
retTime = retTime <= 0.0 ? 1.0 : retTime;
return [NSString stringWithFormat:@"%.0f分钟前", retTime];
} else if (time < 3600 * 24) { // 小于一天,也就是今天

这篇博客详细介绍了在iOS开发中如何根据Date对象计算并返回过去的时间描述,如x分钟前、x小时前、昨天、x天前、x个月前和x年前。这对于创建用户友好的时间显示非常有用。
最低0.47元/天 解锁文章
2171

被折叠的 条评论
为什么被折叠?



