Sort NSDate in order while ignoring time

…衆ロ難τιáo~ 提交于 2019-12-05 06:15:37

问题


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:


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.



来源:https://stackoverflow.com/questions/4355765/sort-nsdate-in-order-while-ignoring-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!