ios 计算时间差

作者: 瞪凳 | 来源:发表于2016-12-05 10:10 被阅读84次

    +(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 @"刚刚";
    }

    相关文章

      网友评论

      • 风茗夜雨:代码中的type 在哪里定义的??
        瞪凳:@怡红公子潇湘馆 不好意思 这个是以前项目里,两种参数类型 忘删了

      本文标题:ios 计算时间差

      本文链接:https://www.haomeiwen.com/subject/xbekmttx.html