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".
Asked
Active
Viewed 4,932 times
1 Answers
4
See this post for sorting an array containing NSDate objects:
Sort NSArray of date strings or objects
and mine for removing the time:
Truncate NSDate (Zero-out time)
ADDITION
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) Now that you have a new array consisting of NSDate objects with zeroed time components, you can sort them:
[newDateArray sortUsingSelector:@selector(compare:)];
This line sorts the array using the NSDate object's own comparator method.

Community
- 1
- 1

Evan Mulawski
- 54,662
- 15
- 117
- 144