如何比较/排序日期与Objective C中的日期数组

时间:2017-11-11 10:53:23

标签: ios objective-c nsdate

请帮助我......

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

现在我想从n获取上一个/上一个myDate日期。

示例: - 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"
)

现在我想在date1date2之间存储/获取日期

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

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

我怎么能这样做,请帮助我。

1 个答案:

答案 0 :(得分:0)

@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);