1.具体使用
//*****************************************************************************************************
//制作key标志 利用set的唯一性
NSMutableSet *set = [NSMutableSet set];
for (ProfitDetailsModel *model in _listArray) {
[set addObject:[self deleteTime:model.taskDate]];
}
//遍历set 同时构造日期相同的数组
for (NSString *key in set) {
NSMutableArray *subArr = [NSMutableArray array];
for (ProfitDetailsModel *model in _listArray) {
//如果时间相同
if([key isEqualToString:[self deleteTime:model.taskDate]]){
[subArr addObject:model];
}
}
[_resultDic setObject:subArr forKey:key];
}
//打印数据 遍历dic
for (NSString * key in _resultDic.allKeys) {
NSLog(@"-----------------------日期为%@的数组有:-----------------",key);
for (ProfitDetailsModel *model in _resultDic[key]) {
NSLog(@"%@\t\t",model.taskDate);
}
}
NSArray *sortArray = [_resultDic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
//排序操作
NSComparisonResult resuest = [obj2 compare:obj1];
return resuest;
}];
//打印数据 遍历dic
for (NSString * key in sortArray) {
NSLog(@"*******************日期为%@的数组有:**********************",key);
for (ProfitDetailsModel *model in _resultDic[key]) {
NSLog(@"%@\t\t",model.taskDate);
}
}
2.需要调用到的方法
//字典key显示的文字(刚刚、今天、昨天、一周前、一月前)
- (NSString *)formateDate:(NSString *)dateString
{
@try {
// ------实例化一个NSDateFormatter对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];//这里的格式必须和DateString格式一致
NSDate * nowDate = [NSDate date];
// ------将需要转换的时间转换成 NSDate 对象
NSDate * needFormatDate = [dateFormatter dateFromString:dateString];
// ------取当前时间和转换时间两个日期对象的时间间隔
NSTimeInterval time = [nowDate timeIntervalSinceDate:needFormatDate];
// NSLog(@"time----%f",time);
// ------再然后,把间隔的秒数折算成天数和小时数:
NSString *dateStr = [[NSString alloc] init];
if (time<=60) { //1分钟以内的
dateStr = @"刚刚";
}else if(time<=60*60){ //一个小时以内的
int mins = time/60;
dateStr = [NSString stringWithFormat:@"%d分钟前",mins];
}else if(time<=60*60*24){ //在两天内的
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSString * need_yMd = [dateFormatter stringFromDate:needFormatDate];
NSString *now_yMd = [dateFormatter stringFromDate:nowDate];
[dateFormatter setDateFormat:@"HH:mm"];
if ([need_yMd isEqualToString:now_yMd]) {
//在同一天
dateStr = [NSString stringWithFormat:@"今天"/*,[dateFormatter stringFromDate:needFormatDate]*/];
}else{
//昨天
dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
}
}else {
[dateFormatter setDateFormat:@"yyyy"];
NSString * yearStr = [dateFormatter stringFromDate:needFormatDate];
NSString *nowYear = [dateFormatter stringFromDate:nowDate];
if ([yearStr isEqualToString:nowYear]) {
//在同一年
[dateFormatter setDateFormat:@"MM-dd"];
dateStr = [dateFormatter stringFromDate:needFormatDate];
}else{
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
dateStr = [dateFormatter stringFromDate:needFormatDate];
}
}
return dateStr;
}
@catch (NSException *exception) {
return @"";
}
}
主要应用在按日期分段排序的订单、活动信息等地方。
此文章仅自己记录用,不做交流使用