iOS 计算某个时间到现在是多少月/天/时的代码

jopen 11年前

传入一个NSString类型的日期

格式如newsDate = @"2013-08-09 17:01";

或者newsDate = @"2013/08/09 17:01";

返回如果有一个月,就不返回天,依次类推。

-(NSString *)getUTCFormateDate:(NSString *)newsDate  {  //    newsDate = @"2013-08-09 17:01";      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];      [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];            NSLog(@"newsDate = %@",newsDate);      NSDate *newsDateFormatted = [dateFormatter dateFromString:newsDate];      NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];      [dateFormatter setTimeZone:timeZone];        NSDate* current_date = [[NSDate alloc] init];            NSTimeInterval time=[current_date timeIntervalSinceDate:newsDateFormatted];//间隔的秒数      int month=((int)time)/(3600*24*30);      int days=((int)time)/(3600*24);      int hours=((int)time)%(3600*24)/3600;      int minute=((int)time)%(3600*24)/60;      NSLog(@"time=%d",(double)time);            NSString *dateContent;            if(month!=0){                    dateContent = [NSString stringWithFormat:@"%@%i%@",@"   ",month,@"个月前"];        }else if(days!=0){                     dateContent = [NSString stringWithFormat:@"%@%i%@",@"   ",days,@"天前"];      }else if(hours!=0){                     dateContent = [NSString stringWithFormat:@"%@%i%@",@"   ",hours,@"小时前"];      }else {                dateContent = [NSString stringWithFormat:@"%@%i%@",@"   ",minute,@"分钟前"];      }        //    NSString *dateContent=[[NSString alloc] initWithFormat:@"%i天%i小时",days,hours];                  [current_date release];      [dateFormatter release];      return dateContent;  }