在忽略时间的情况下按顺序对 NSDate 进行排序 [英] Sort NSDate in order while ignoring time
问题描述
我只想在 NSDates 的日期、月份和年份对数组进行排序,而不是按任何时间单位排序.我该怎么做,因为我看不到将 NsDate 的各个部分输出"的方法.
I want to sort an array of NSDates only on their day month and year so not on any of the units of time. How can I do this because I can't see a way of getting the individual parts of an NsDate "out".
推荐答案
查看这篇文章以对包含 NSDate 对象的数组进行排序:
See this post for sorting an array containing NSDate objects:
和我的删除时间:
添加
1) 遍历您的 NSDate 对象数组,删除(归零)时间分量,并将它们添加到新数组中:
1) Loop through your array of NSDate objects, removing (zeroing) the time components, and adding them to a new array:
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 对象组成的新数组,其中的时间分量为零,您可以对它们进行排序:
2) Now that you have a new array consisting of NSDate objects with zeroed time components, you can sort them:
[newDateArray sortUsingSelector:@selector(compare:)];
这一行使用 NSDate 对象自己的比较器方法对数组进行排序.
This line sorts the array using the NSDate object's own comparator method.
这篇关于在忽略时间的情况下按顺序对 NSDate 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!