Search code examples
objective-cxcodedatetimensdate

NSDateComponents - set weekday components


I am trying to check if a 2 dates and times are in-between the current time. I have made this function to do so. Here is the function

-(BOOL)getStartHour:(NSInteger)startHour getStartMin:(NSInteger)startMin getEndHour:

(NSInteger)endHour getEndMin:(NSInteger)endMin {
    NSDate *now = [NSDate date];
    NSDate *startOfToday;
    [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&startOfToday interval:NULL forDate:now];


    NSDateComponents *startComps = [[NSDateComponents alloc] init];
    startComps.weekday = 1;
    startComps.hour = startHour;
    startComps.minute = startMin;
//
    NSDateComponents *endComps = [[NSDateComponents alloc] init];
    endComps.hour = endHour;
    endComps.minute = endMin;
    endComps.weekday = 3;

    NSDate *startDate =  [[NSCalendar currentCalendar] dateByAddingComponents:startComps toDate:startOfToday options:0];
    NSDate *endDate =  [[NSCalendar currentCalendar] dateByAddingComponents:endComps toDate:startOfToday options:0];
    NSLog(@"%d", [startComps weekday]);
//    NSLog(@"%@", startDate);
//    NSLog(@"%@", now);

    if ([startDate timeIntervalSince1970] < [now timeIntervalSince1970] && [now timeIntervalSince1970]  < [endDate timeIntervalSince1970]) {
        return YES;
    }
    else return NO;
}

When I log [startComps weekday] it logs, 0. But today is Tuesday which makes no sense to me. I want to check if this date is between Monday and Wednesday day which I would guess as 1 - 3 or 0 - 2. But why is it logging today (Tuesday) as 0?

In others words I am looking for a dayOfWeek as an integer. SO monday - 1, tuesday 2 and so on

Thakns for the help in advance.


Solution

  • if ([startDate timeIntervalSince1970] < [now timeIntervalSince1970] && [now timeIntervalSince1970]  < [endDate timeIntervalSince1970]) {
            return YES;
        }
        else return NO;
    

    And then return it day by day,

    so add in the if statement

    if weekday < day and day < weekend 
    return yes