//转换创建时间的格式
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
fmt.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
NSDate *createdDate = [fmt dateFromString:_created_at];
//NSDate *createdDate = [fmt dateFromString:@"Thu May 19 13:20:20 +0800 2014"];
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *createdStr = [fmt stringFromDate:createdDate];
createdDate = [fmt dateFromString:createdStr];
NSDate *now = [NSDate date];//2015-05-22 14:16:16 +0000
NSCalendar *calender = [NSCalendar currentCalendar];
//why?
NSDateComponents *compareComponents = [calender components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ) fromDate:createdDate toDate:now options:0]; //!!!!!!!
//NSLog(@"%@",compareComponents);
NSDateComponents *createdComponents = [calender components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:createdDate];
NSDateComponents *nowComponents = [calender components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:now];
BOOL isThisYear = createdComponents.year == nowComponents.year;
BOOL isToday = createdComponents.month == nowComponents.month && createdComponents.day == nowComponents.day;
BOOL isYesterday = createdComponents.month == nowComponents.month && compareComponents.day == 1;
if (isThisYear) { //今年
if (isToday) {//今天
if (fabs([now timeIntervalSinceDate:createdDate]) < 60) {//小于一分钟
return @"刚刚";
} else if (compareComponents.hour == 0) { //小于一个小时
return [NSString stringWithFormat:@"%ld分钟前",compareComponents.minute];
} else { //大于一个小时
return [NSString stringWithFormat:@"%ld小时前",compareComponents.hour];
}
} else if (isYesterday) { //昨天
fmt.dateFormat = @"HH:mm:ss";
NSString *str = [fmt stringFromDate:createdDate];
return [NSString stringWithFormat:@"昨天 %@",str];
} else { //今年的其他日子
fmt.dateFormat = @"MM-dd HH:mm:ss";
return [fmt stringFromDate:createdDate];
}
} else {//其他年份
return [fmt stringFromDate:createdDate];
}
iOS日期处理
最新推荐文章于 2024-09-10 17:30:17 发布