只在两个日期之间获得周末

时间:2012-01-26 19:16:42

标签: objective-c cocoa time nsdate nscalendar

我正在尝试只在两个日期之间的周六和周日,但我不知道为什么让我在一周内获得免费日。

这是我的代码:

- (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;

2 个答案:

答案 0 :(得分:2)

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];
}

答案 1 :(得分:1)

要记住的一件非常重要的事情是一天不一定(必然)等于24 * 60 * 60秒。你不应该自己做日期算术

你真正需要做的事情似乎有点单调乏味但这是正确的做法:使用NSCalendar– dateByAddingComponents:toDate:options:

请参阅Calendrical Calculations指南。