如何在iPhone中的两个给定日期之间仅获得星期六日期

时间:2013-08-19 04:23:46

标签: ios cocoa-touch nsdate

我正在尝试仅提取星期六两个给定日期之间的日期。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

不幸的是,没有直接的方法在两个日期之间循环,你无法直接从NSDate对象获得工作日。因此,您需要添加几行才能使其正常工作。这里的关键是使用NSDateComponents。在这个例子中,我使用的是公历。默认情况下,根据Apple的文档,工作日从周日开始,即第一天(字面意思为1)。请不要认为周日是零(通常会感到困惑)。

知道,星期六是本周的第七天,所以我们可以说它是整数7.这是代码。从这里,您可以轻松创建一个方法来添加到您的类/类别,并将您想要检查的工作日作为参数传递。

NSInteger count = 0;
NSInteger saturday = 7;

// Set the incremental interval for each interaction.
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:1];

// Using a Gregorian calendar.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDate *currentDate = fromDate;

// Iterate from fromDate until toDate
while ([currentDate compare:toDate] == NSOrderedAscending) {

    NSDateComponents *dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:currentDate];

    if (dateComponents.weekday == saturday) {
        count++;
    }

    // "Increment" currentDate by one day.
    currentDate = [calendar dateByAddingComponents:oneDay
                                            toDate:currentDate
                                           options:0];
}

NSLog(@"count = %d", count);

答案 1 :(得分:1)

您可以使用以下方法:

-(NSArray*)specificdaysInCalendar:(NSArray*)holidays   {
    //if you want saturdays, thn you have to pass 7 in the holidays array
    NSDate *startdate = START_DATE;
    NSDate *endDate = END_DATE;
    NSDateComponents *dayDifference = [[NSDateComponents alloc] init];

    NSMutableArray *dates = [[NSMutableArray alloc] init] ;
    NSUInteger dayOffset = 1;
    NSDate *nextDate = startdate;
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] ;

    do {
        NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:nextDate];
        int weekday = [comps weekday];
        //NSLog(@"%i,%@",weekday,nextDate);
        if ([holidays containsObject:[NSString stringWithFormat:@"%i",weekday]]) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];

            dateFormatter.dateFormat = @"dd/MM/yyyy";

            NSString *dateString = [dateFormatter stringFromDate:nextDate];
            NSDate *outDate = [dateFormatter dateFromString:dateString];
            //NSLog(@"%@,%@,%@",nextDate,dateString,outDate);
            [dates addObject:outDate];
        }


        [dayDifference setDay:dayOffset++];
        NSDate *d = [[NSCalendar currentCalendar] dateByAddingComponents:dayDifference toDate:startdate options:0];

        nextDate = d;
    } while([nextDate compare:endDate] == NSOrderedAscending);

    return dates;

}

在参数数组

中传递星期六的数字7