作为替代方案,您可以通过依赖从两个日期之间获取的日历组件来避免容易出错的日历算术:
NSDate *nowDate = [[NSDate alloc] init];
NSDate *targetDate = nil;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:dateTime
toDate:nowDate options:0];
NSInteger months = [components month];
NSInteger weeks = [components week];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger minutes = [components minute];
关键是设置单位标志 - 这允许您设置要将日期/时间分解为哪些时间单位。如果您只想要小时,则会设置NSHourCalendarUnit,随着您的日期之间的距离增加,该值将继续增加,因为没有更大的单位开始递增。
一旦您获得了组件,您可以根据自己的选择进行逻辑处理,例如修改@alex的条件流程。
这就是我凑在一起的内容:
if (months > 1) {
if (weeks >3) {
months++;
}
return [NSString stringWithFormat:@"%ld months ago", (long)months];
}
else if (months == 1) {
if (weeks > 3) {
months++;
return [NSString stringWithFormat:@"%ld months ago", (long)months];
}
return [NSString stringWithFormat:@"1 month ago"];
}
else if (weeks > 1) {
if (days > 6) {
weeks++;
}
return [NSString stringWithFormat:@"%ld weeks ago", (long)weeks];
}
else if (weeks == 1 ||
days > 6) {
if (days > 6) {
weeks++;
return [NSString stringWithFormat:@"%ld weeks ago", (long)weeks];
}
return [NSString stringWithFormat:@"1 week ago"];
}
else if (days > 1) {
if (hours > 20) {
days++;
}
return [NSString stringWithFormat:@"%ld days ago", (long)days];
}
else if (days == 1) {
if (hours > 20) {
days++;
return [NSString stringWithFormat:@"%ld days ago", (long)days];
}
return [NSString stringWithFormat:@"1 day ago"];
}
else if (hours > 1) {
if (minutes > 50) {
hours++;
}
return [NSString stringWithFormat:@"%ld hours ago", (long)hours];
}
else if (hours == 1) {
if (minutes > 50) {
hours++;
return [NSString stringWithFormat:@"%ld hours ago", (long)hours];
}
return [NSString stringWithFormat:@"1 hour ago"];
}
else if (minutes > 1) {
return [NSString stringWithFormat:@"%ld minutes ago", (long)minutes];
}
else if (minutes == 1) {
return [NSString stringWithFormat:@"1 minute ago"];
}
else if (minutes < 1) {
return [NSString stringWithFormat:@"Just now"];
}