我正在尝试仅获取两个日期之间的星期六和星期日,但我不知道为什么要让我一周有空。

这是我的代码:

- (BOOL)checkForWeekend:(NSDate *)aDate {
    BOOL isWeekendDate = NO;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange weekdayRange = [calendar maximumRangeOfUnit:NSWeekdayCalendarUnit];
    NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:aDate];
    NSUInteger weekdayOfDate = [components weekday];

    if (weekdayOfDate == weekdayRange.location || weekdayOfDate == weekdayRange.length) {
        // The date falls somewhere on the first or last days of the week.
        isWeekendDate = YES;
    }
    return isWeekendDate;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    NSString *strDateIni = [NSString stringWithString:@"28-01-2012"];
    NSString *strDateEnd = [NSString stringWithString:@"31-01-2012"];

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"dd-MM-yyyy"];
    NSDate *startDate = [df dateFromString:strDateIni];
    NSDate *endDate = [df dateFromString:strDateEnd];

    unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate  toDate:endDate  options:0];

   // int months = [comps month];
    int days = [comps day];

    for (int i=0; i<days; i++)
    {

        NSTimeInterval interval = i;
        NSDate * futureDate = [startDate dateByAddingTimeInterval:interval];

        BOOL isWeekend = [self checkForWeekend:futureDate]; // Any date can be passed here.

        if (isWeekend) {
            NSLog(@"Weekend date! Yay!");
        }
        else
        {
            NSLog(@"Not is Weekend");
        }


    }

}


问题:
此问题是由NSTimeInterval interval = i;引起的。for循环的逻辑是逐日迭代。将时间间隔设置为i,以秒为单位进行迭代。

来自关于NSTimeInterval的文档


  NSTimeInterval始终以秒为单位;


答案:

NSTimeInterval行更改为

NSTimeInterval interval = i*24*60*60;

最佳答案

Here is a link to another answer我在SO上发贴(我知道,不要脸)。它包含一些代码,可能会帮助您确定将来的日期。这些方法被实现为NSDate的类别,这意味着它们成为NSDate的方法。

周末有一些功能可以帮助您。但是以下两个可能最有帮助:

- (NSDate*) theFollowingWeekend;
- (NSDate *) thePreviousWeekend;


他们返回接收者(自己)之后和之前的周末日期。

通常,您不应使用一天为86400秒的概念,而应使用NSDateComponents和NSCalendar。即使在两个日期之间发生夏令时转换时,此方法也有效。像这样:

- (NSDate *) dateByAddingDays:(NSInteger) numberOfDays {
    NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
    dayComponent.day = numberOfDays;

    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    return [theCalendar dateByAddingComponents:dayComponent toDate:self options:0];
}

关于objective-c - 仅获取两个日期之间的周末,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9023891/

10-11 22:36
查看更多