标签:
1 // 1.把帖子发布时间字符串转换成(NSDate)日期对象 => NSDateFormatter 2 // NSDateFormatter:NSStreing与NSDate互转 3 NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; 4 // 设置格式 5 fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss"; 6 // 发布日期对象 7 NSDate *createDate = [fmt dateFromString:item.create_time]; 8 9 // 获取日历类对象 10 // NSCalendar *calendar = [NSCalendar currentCalendar]; 11 // 获取日期组件 12 // NSDateComponents *cmp = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute fromDate:createDate toDate:[NSDate date] options:NSCalendarWrapComponents]; 13 14 NSString *timeStr = item.create_time; 15 if ([createDate isThisYear]) { 16 if ([createDate isThisToday]) { 17 18 // 获取日期差值 19 if (cmp.hour >= 1) { 20 timeStr = [NSString stringWithFormat:@"%ld小时前",cmp.hour]; 21 } else if (cmp.minute >= 2) { 22 timeStr = [NSString stringWithFormat:@"%ld分钟前",cmp.minute]; 23 } else { // 刚刚 24 timeStr = @"刚刚"; 25 } 26 } else if ([createDate isThisYesterday]) { // 昨天 27 // 昨天 21:10 28 fmt.dateFormat = @"昨天 HH:mm"; 29 timeStr = [fmt stringFromDate:createDate]; 30 31 } else { // 昨天之前 08-05 21:10:08 32 fmt.dateFormat = @"MM-dd HH:mm:ss"; 33 timeStr = [fmt stringFromDate:createDate]; 34 } 35 } 36 37 因为判断日期要常用,我们就把判断方法抽取到NSDate的分类 38 39 - (BOOL)isThisYear 40 { 41 // 获取当前日期对象 42 NSDate *curDate = [NSDate date]; 43 // 获取日历类 44 NSCalendar *curCalendar = [NSCalendar currentCalendar]; 45 // 获取自己日期组件(年,月,等) self代码外面调用这个方法的日历类(也就是createDate) 46 NSDateComponents *selfCmp = [curCalendar components:NSCalendarUnitYear fromDate:self]; 47 // 获取当前时间日期组件(年,月,等) 48 NSDateComponents *curCmp = [curCalendar components:NSCalendarUnitYear fromDate:curDate]; 49 return curCmp.year == selfCmp.year; 50 } 51 52 // 判断是否是今天 53 - (BOOL)isThisToday 54 { 55 // 获取日历类 56 NSCalendar *curCalendar = [NSCalendar currentCalendar]; 57 return [curCalendar isDateInToday:self]; 58 } 59 60 - (BOOL)isThisYesterday 61 { 62 NSCalendar *curCalendar = [NSCalendar currentCalendar]; 63 return [curCalendar isDateInYesterday:self]; 64 }
标签:
原文地址:http://www.cnblogs.com/xiaotian666/p/5760798.html