1

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".

1 Answer 1

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.