Sort NSDate without respect to the time of day - just the date

不想你离开。 提交于 2019-12-24 03:07:41

问题


I have an array controller with keys of nextCheck (NSDate), lastName (NSString), and firstName (NSString). I have set the sort descriptors for the array. As you can see below, I am sorting by nextCheck first, then lastName, then firstName. This appears to not be working because the NSDate is made up of not only a date component but also a time component. Is there an easy way to sort by the date component only?

[_arrayCurrentVisits setSortDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"nextVisit" ascending:YES selector:@selector(compare:)],[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)], [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)], nil]];

回答1:


The simplest solution would be to add a method called nextVisitDate returning the value of nextVisit "truncated" to midnight, and sort on nextVisitDate instead.

[_arrayCurrentVisits setSortDescriptors:[ //                           vvv HERE vvv
    NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"nextVisitDate"  ascending:YES selector:@selector(compare:)]
,   [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]
,   [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]
,   nil]];



回答2:


What I did, was when I created dates I only used the date components of the date:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) 
                                          fromDate:[NSDate date]];
NSDate *currentDate = [calendar dateFromComponents:comps];


来源:https://stackoverflow.com/questions/8651733/sort-nsdate-without-respect-to-the-time-of-day-just-the-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!