【问题标题】:Get all dates of same day from array从数组中获取同一天的所有日期
【发布时间】:2023-03-14 19:07:01
【问题描述】:
假设我有不同日期的 NSMutableArray。日期在 UITableView 中表示。如果我单击 UITableViewCell,如何从 NSMutableArray 获取同一天的所有日期?
假设我在星期一插入了 3 个日期,在星期二插入了 1 个日期,在星期三插入了 4 个日期,依此类推...如果我按代表星期一的 1/3 日期,我怎样才能得到所有 3 个星期一的日期并忽略其他日子??
如果可能的话,我该如何对它们进行排序?因此,如果我在 8、9、10 小时内保存(全部在星期一),然后按任意小时(还包括分钟),它们将按照 8-9-10 的顺序进行排序,这与它们实际发生的情况完全相同...
Tnx.
【问题讨论】:
标签:
objective-c
date
sorting
nsdate
【解决方案1】:
使用 NSDate 和 company 计算日期有点复杂,但一旦你掌握了它,它实际上非常强大。这是过滤数组的一种方法:
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSMutableArray *dates = [NSMutableArray array];
NSDate *selectedDate = [NSDate date];
for (int i=0; i<70; i++)
[dates addObject:[NSDate dateWithTimeIntervalSinceNow:i * 60*60*24]];
NSInteger selectedDayOfWeek = [calendar components:NSWeekdayCalendarUnit fromDate:selectedDate].weekday;
NSPredicate *filter = [NSPredicate predicateWithBlock:^(id object, NSDictionary *bindings) {
return (BOOL)([calendar components:NSWeekdayCalendarUnit fromDate:object].weekday == selectedDayOfWeek);
}];
NSArray *filteredDates = [dates filteredArrayUsingPredicate:filter];
NSArray *sortedDates = [filteredArray sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@", filteredDates);
}
return 0;
}