ios 计算时间差

+(NSString *)getTimeDifferenceWithString:(NSString *)string
{
NSDate * data = [NSDate date];

   NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
   dateFomatter.dateFormat = @"yyyy-MM-dd HH:mm";

   //当前时间
   NSString * nowDateString = [dateFomatter stringFromDate:data];
   data = [dateFomatter dateFromString:nowDateString];

   NSTimeInterval timeNo;
   NSDate * date;
   NSString * time;
   NSDate * expirDate;
 
     timeNo = [string doubleValue];
     date = [NSDate dateWithTimeIntervalSince1970:timeNo];
     time = [dateFomatter stringFromDate:date];  

   //截止时间
   expirDate = [dateFomatter dateFromString:time];
   NSCalendar * calendar = [NSCalendar currentCalendar];

   NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth|    NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;

   NSDateComponents *dateCom = [calendar components:unit fromDate:data toDate:expirDate options:0];

   if (dateCom.year<0)
   {
     return [NSString stringWithFormat:@"%ld年前",(long)-dateCom.year];
   }
   else if (dateCom.month<0)
   {
     return [NSString stringWithFormat:@"%ld月前",(long)-dateCom.month];
   }
   else if (dateCom.day<0)
   {
     return [NSString stringWithFormat:@"%ld天前",(long)-dateCom.day];
   }
   else if (dateCom.hour<0)
   {
     return [NSString stringWithFormat:@"%ld小时前",(long)-dateCom.hour];
   }
   else if (dateCom.minute<0)
   {
     return [NSString stringWithFormat:@"%ld分钟前",(long)-dateCom.minute];
   }

   return @"刚刚";
}

你可能感兴趣的:(ios 计算时间差)