Note that there are some explanatory texts on larger screens.

plurals
  1. POGet only weekends between two dates
    primarykey
    data
    text
    <p>I'm trying get only the Saturdays and Sundays between two dates, but I don't know why get me free days on a week.</p> <p>Here is my code: </p> <pre><code>- (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&lt;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"); } } } </code></pre> <p>The problem: The issue was caused by <code>NSTimeInterval interval = i;</code> The logic of the for loop was to iterate by days. Setting the time interval to i was iterating by seconds.</p> <p>From documentation on NSTimeInterval</p> <blockquote> <p>NSTimeInterval is always specified in seconds;</p> </blockquote> <p>The answer:</p> <p>Changing the <code>NSTimeInterval</code> line to </p> <pre><code>NSTimeInterval interval = i*24*60*60; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload