Objective c 按顺序排序NSDate,而忽略时间
我只想按日期、月份和年份对NSDate数组进行排序,而不是按任何时间单位进行排序。我怎么能做到这一点,因为我看不到一种方法来“输出”NsDate的各个部分 有关对包含NSDate对象的数组进行排序的信息,请参阅本文: 和我的时间: 添加 1) 在NSDate对象数组中循环,删除(归零)时间组件,并将其添加到新数组中:Objective c 按顺序排序NSDate,而忽略时间,objective-c,nsdate,Objective C,Nsdate,我只想按日期、月份和年份对NSDate数组进行排序,而不是按任何时间单位进行排序。我怎么能做到这一点,因为我看不到一种方法来“输出”NsDate的各个部分 有关对包含NSDate对象的数组进行排序的信息,请参阅本文: 和我的时间: 添加 1) 在NSDate对象数组中循环,删除(归零)时间组件,并将其添加到新数组中: NSMutableArray *newDateArray = [NSMutableArray array]; for (NSDate *d in myDateArray) {
NSMutableArray *newDateArray = [NSMutableArray array];
for (NSDate *d in myDateArray)
{
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:d];
//Taking the time zone into account
NSDate *dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
[newDateArray addObject:dateOnly];
}
2) 现在您有了一个由NSDate对象和零时间组件组成的新数组,您可以对它们进行排序:
[newDateArray sortUsingSelector:@selector(compare:)];
此行使用NSDate对象自己的比较器方法对数组进行排序。有关对包含NSDate对象的数组进行排序的信息,请参阅本文: 和我的时间: 添加 1) 在NSDate对象数组中循环,删除(归零)时间组件,并将其添加到新数组中:
NSMutableArray *newDateArray = [NSMutableArray array];
for (NSDate *d in myDateArray)
{
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:d];
//Taking the time zone into account
NSDate *dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
[newDateArray addObject:dateOnly];
}
2) 现在您有了一个由NSDate对象和零时间组件组成的新数组,您可以对它们进行排序:
[newDateArray sortUsingSelector:@selector(compare:)];
此行使用NSDate对象自己的比较器方法对数组进行排序