ios-计算时间方法
-(NSString *)countPublishTime:(NSString *)sDate
{
NSDate *dtNow = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:sDate];
if (date == nil) {
return @"";
}
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSDayCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:date toDate:dtNow options:0];
NSInteger days = [comps day];
NSInteger hours;// = [comps hour];
NSString *sTime = nil;
NSInteger minute;// = [comps minute];
if (days==0) {
unitFlags = NSHourCalendarUnit;
comps = [gregorian components:unitFlags fromDate:date toDate:dtNow options:0];
hours = [comps hour];
if (hours == 0) {
unitFlags = NSMinuteCalendarUnit;
comps = [gregorian components:unitFlags fromDate:date toDate:dtNow options:0];
minute = [comps minute];
if (minute == 0||minute<0) {
sTime = @"刚刚";
}
else sTime = [NSString stringWithFormat:@"%d分钟前",minute];
}
else sTime = [NSString stringWithFormat:@"%d小时前",hours];
}
else sTime = [NSString stringWithFormat:@"%d天前",days];
return sTime;
}
调用
NSString *sTime =[self countPublishTime:obj.strPara08];