-4

我试图只获取两个给定日期之间星期六的日期。

我怎样才能做到这一点?

4

2 回答 2

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);
于 2013-08-19T05:44:46.297 回答
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

于 2013-08-19T04:30:49.643 回答