如何 compare/sort 与 Objective C 中的日期数组约会

How to compare/sort date with array of dates in Objective C

请帮助我...

我将当前系统日期存储在变量 myDate 中,即 myDate = 11 Nov 2017

现在我想从 myDate 获取 last/previous n 日期。

示例:- n = 7

myDate - 7 => 05 Nov 17

现在我得到了 date1 (currentDate) = 11 November 17 && date2 (previous n date) = 05 November 17

我已经从我的核心数据中获取了数据,这给了我这个日期数组:

(
    "11 November 2017",
    "10 November 2017",
    "8 November 2017",
    "5 November 2017",
    "3 November 2017",
    "1 November 2017"
)

现在我想 store/fetch 在 date1date2

之间的日期

所以最后我应该得到这个数组:

(
        "11 November 2017",
        "10 November 2017",
        "8 November 2017",
        "5 November 2017"
 )

我该怎么办,请帮帮我。

@Aadi 试试这个..

NSMutableArray *arrOutput = [[NSMutableArray alloc]init];
    NSMutableArray *arrDates = [[NSMutableArray alloc]initWithObjects:@"11 November 2017",
                                @"10 November 2017",
                                @"8 November 2017",
                                @"5 November 2017",
                                @"3 November 2017",
                                @"1 November 2017", nil];
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"dd MMMM yyyy"];
    [df setTimeZone:[NSTimeZone localTimeZone]];
    NSString *strCurrentDate = [df stringFromDate:[NSDate date]];
    NSDate *currentDate = [df dateFromString:strCurrentDate];

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
    dayComponent.day = -7;
    NSDate *lastWeek = [gregorian dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];

    for(int i=0; i<arrDates.count; i++)
    {
        NSDate *dateFormArray = [df dateFromString:[arrDates objectAtIndex:i]];
        if ([dateFormArray compare:currentDate] == NSOrderedAscending && [dateFormArray compare:lastWeek] != NSOrderedAscending)
        {
            [arrOutput addObject:[arrDates objectAtIndex:i]];
        }
    }
    NSLog(@"current date = %@",strCurrentDate);
    NSLog(@"output = %@",arrOutput);