格式1 通过(2014-12-11 22:22:22) 获得 今天22:22 ,昨天22:22 , 2天前 , 1个月前 , 3年前
NSString *dateStr = @"2015-01-15 22:22:22";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSRange r = [dateStr rangeOfString:@"-" options:NSBackwardsSearch]; // 找出最后一个-所在的位置
NSDate *date = [dateFormat dateFromString:[dateStr substringToIndex:r.location + 3]];
NSTimeInterval time = [[NSDate date] timeIntervalSinceDate:date]; // 获取date距离系统时间的总共秒数
int year = ((int)time / (3600 * 24 * 30 * 12));
int month = ((int)time / (3600 * 24 * 30));
int day = ((int)time / (3600 * 24));
NSString *dateContent;
if (year != 0) {
dateContent = [NSString stringWithFormat:@"%i年前", year];
} else if (month != 0) {
dateContent = [NSString stringWithFormat:@"%i个月前", month];
} else {
r = [dateStr rangeOfString:@":"];
if (day == 0) {
dateContent = [NSString stringWithFormat:@"今天 %@", [dateStr substringWithRange:NSMakeRange(r.location - 2, 5)]];
} else if (day == 1) {
dateContent = [NSString stringWithFormat:@"昨天 %@", [dateStr substringWithRange:NSMakeRange(r.location - 2, 5)]];
} else {
dateContent = [NSString stringWithFormat:@"%i天前", day];
}
}
格式2 通过(2003-22-22 12:22:33) 获得 刚刚 , 20秒前 , 3分钟前 , 1小时前 , 2天前 , 1周前 , 5个月前 , 2年前
NSString *dateStr = @"2015-01-15 12:11:11";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:dateStr];
double deltaSeconds = fabs([[NSDate date] timeIntervalSinceDate:date]); // 获取总共秒数
double deltaMinutes = deltaSeconds / 60.0f;
NSString *dateContent;
if (deltaSeconds < 5) {
dateContent = @"刚刚";
} else if (deltaSeconds < 120) {
dateContent = @"1分钟前";
} else if (deltaMinutes < 60) {
dateContent = [NSString stringWithFormat:@"%i分钟前", (int)deltaMinutes];
} else if (deltaMinutes < 120) {
dateContent = @"1小时前";
} else if (deltaMinutes < (24 * 60)) {
dateContent = [NSString stringWithFormat:@"%i小时前", (int)floor(deltaMinutes / 60)];
} else if (deltaMinutes < (24 * 60 * 2)) {
dateContent = @"昨天";
} else if (deltaMinutes < (24 * 60 * 7)) {
dateContent = [NSString stringWithFormat:@"%d天前", (int)floor(deltaMinutes/(60 * 24))];
} else if (deltaMinutes < (24 * 60 * 14)) {
dateContent = @"上周";
} else if (deltaMinutes < (24 * 60 * 31)) {
dateContent = [NSString stringWithFormat:@"%d周前", (int)floor(deltaMinutes/(60 * 24 * 7))];
} else if (deltaMinutes < (24 * 60 * 61)) {
dateContent = @"上个月";
} else if (deltaMinutes < (24 * 60 * 365.25)) {
dateContent = [NSString stringWithFormat:@"%d月前", (int)floor(deltaMinutes/(60 * 24 * 30))];
} else if (deltaMinutes < (24 * 60 * 731)) {
dateContent = @"去年";
} else {
dateContent = [NSString stringWithFormat:@"%i年前", (int)floor(deltaMinutes/(60 * 24 * 731))];
}