Piero Piero - 3 months ago 22
iOS Question

Check if NSDate is in this week or next week

there is a way to check if an NSDate is this week or is next week?

i know that today is:

[NSDate date]


and then how i can do?

Edu Edu
Answer

Use NSDateComponents, something like this:

NSCalendar *gregorian = [[NSCalendar alloc]
    initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *today = [NSDate date];

    NSDateComponents *todaysComponents =
        [gregorian components:NSWeekCalendarUnit fromDate:date];

    NSUInteger todaysWeek = [todaysComponents week];


    NSDate *anotherDate = [NSDate date];

    NSDateComponents *otherComponents =
        [gregorian components:NSWeekCalendarUnit fromDate:anotherDate];

    NSUInteger anotherWeek = [otherComponents week];

    if(todaysWeek==anotherWeek){
         NSLog(@"another date is this week");
    }else if(todaysWeek+1==anotherWeek){
         NSLog(@"another date is next week")
    }

You can also use other components like month or year to be completely sure.

NOTE: Don't use timeIntervals. By using NSDateComponents you ignore the hour, minutes and seconds. I think you want that.