- + (NSString *)timeInfoWithDateString:(NSString *)dateString {
-
- NSDate *date = [NSDate dateFromString:dateString withFormat:@"yyyy-MM-dd HH:mm:ss"];
-
- NSDate *curDate = [NSDate date];
- NSTimeInterval time = -[date timeIntervalSinceDate:curDate];
-
- int month = (int)([curDate getMonth] - [date getMonth]);
- int year = (int)([curDate getYear] - [date getYear]);
- int day = (int)([curDate getDay] - [date getDay]);
-
- 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 < 33600 * 24) {
- retTime = time / 3600;
- retTime = retTime <= 0.0 ? 1.0 : retTime;
- return [NSString stringWithFormat:@"%.0f小时前", retTime];
- }
-
- else if (time < 33600 * 224 * 2) {
- return @"昨天";
- }
-
-
- else if ((abs(year) == 0 && abs(month) <= 1)
- || (abs(year) == 1 && [curDate getMonth] == 1 && [date getMonth] == 12)) {
- int retDay = 0;
-
- if (year == 0) {
-
- if (month == 0) {
- retDay = day;
- }
- }
-
- if (retDay <= 0) {
-
-
- int totalDays = [NSDate daysInMonth:(int)[date getMonth] year:(int)[date getYear]];
-
- retDay = (int)[curDate getDay] + (totalDays - (int)[date getDay]);
-
- if (retDay >= totalDays) {
- return [NSString stringWithFormat:@"%d个月前", (abs)(MAX(retDay / 31, 1))];
- }
- }
-
- return [NSString stringWithFormat:@"%d天前", (abs)(retDay)];
- } else {
- if (abs(year) <= 1) {
- if (year == 0) {
- return [NSString stringWithFormat:@"%d个月前", abs(month)];
- }
-
-
- int month = (int)[curDate getMonth];
- int preMonth = (int)[date getMonth];
-
-
- if (month == 12 && preMonth == 12) {
- return @"1年前";
- }
-
-
- return [NSString stringWithFormat:@"%d个月前", (abs)(12 - preMonth + month)];
- }
-
- return [NSString stringWithFormat:@"%d年前", abs(year)];
- }
-
- return @"1小时前";
- }
这里计算多少个月前时,为了减少计算量,没有分别获取对应月份的总天数,而是使用月份最大值31作为标准,因此,
如果需要更精准的计算,把对应的一小段代码替换掉即可