不考虑时间对 NSDate 进行排序 - 只是日期 [英] Sort NSDate without respect to the time of day - just the date

查看:92
本文介绍了不考虑时间对 NSDate 进行排序 - 只是日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 nextCheck (NSDate)、lastName (NSString) 和 firstName (NSString) 键的数组控制器.我已经为数组设置了排序描述符.正如你在下面看到的,我首先按 nextCheck 排序,然后是 lastName,然后是 firstName.这似乎不起作用,因为 NSDate 不仅由日期组件组成,还由时间组件组成.有没有一种简单的方法可以只按日期组件排序?

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]];

推荐答案

最简单的解决方案是 添加一个名为 nextVisitDate 的方法,将截断"的 nextVisit 的值返回到午夜,然后排序nextVisitDate 代替.

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]];

这篇关于不考虑时间对 NSDate 进行排序 - 只是日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆