3

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?

Piero
  • 9,173
  • 18
  • 90
  • 160

7 Answers7

6

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.

Eduardo
  • 1,383
  • 8
  • 13
  • thank you very much this is the best answer :), if is the last week of the year, i have to check with other component to be sure right? – Piero Apr 13 '12 at 15:53
  • Exactly, remember to add the components that you're going to use like this: NSDateComponents *todaysComponents = [gregorian components:(NSWeekCalendarUnit|NSMonthCalendarUnit) fromDate:date]; then, get the components and compare them. – Eduardo Apr 13 '12 at 15:55
  • Ok thanks, because if is a new year the new week unit number is 1 right? – Piero Apr 13 '12 at 16:02
  • Yes, but it's better to compare the year, for example: if the year of anotherDate is the currentYear plus 1, we are sure that anotherDate refers to a date in the next year. – Eduardo Apr 13 '12 at 16:05
  • ok, and then if there is another year i have to check the week to determinate if is next week or in the future, because i want check this week next week or future... – Piero Apr 13 '12 at 16:08
  • 1
    i Can't understand if the year is different, for example if currentYear + 1 == anotherYear so i have to check the week, but if the 31 of December is Thursday and the 1 of January is Wendsday, how work the week number? – Piero Apr 13 '12 at 16:41
  • I think I don't get it :S Give me an example with two dates so I can figure it out. – Eduardo Apr 13 '12 at 18:32
2

pass the 2 dates to this method:

- (BOOL) isSameWeekAsDate: (NSDate *) aDate andDate:(NSDate *) bDate
{
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit) fromDate:aDate];
    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit) fromDate:bDate];

    if ([components1 week] != [components2 week]) return NO;

    //return (abs([self timeIntervalSinceDate:aDate]) < 604800); // ops, forgot to change "self" with parameter "bDate":
    return (abs([bDate timeIntervalSinceDate:aDate]) < 604800);
}

EDIT: call it with 2 dates of different years:

[components setDay:31];
[components setMonth:12];
[components setYear:2010];
NSCalendar *gregorian = [[NSCalendar alloc]  initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date1 = [gregorian dateFromComponents:components];

// second date (SATURDAY -of the same week, other year...)
[components setDay:1];
[components setMonth:1];
[components setYear:2011];
NSDate *date2 = [gregorian dateFromComponents:components];

if ([self isSameWeekAsDate:date1 andDate:date2]) {
    NSLog(@"Same Week!");
}else{
    NSLog(@"OTHER WEEK!");
}
meronix
  • 6,175
  • 1
  • 23
  • 36
  • This will return NO if both dates are in the same week, but different years, I think... – samson Apr 14 '12 at 17:40
  • @samson: mmm, are you sure? let's bet a +1... see my edit to try a call to it. – meronix Apr 14 '12 at 22:38
  • I submit, sir. I tried it, and you are correct. ASSUMING firstWeekday hasn't been set for some strange reason, and you forgot, and are thinking of the wrong week start... in which case year doesn't matter... – samson Apr 15 '12 at 10:18
  • 1
    week is deprecated, weekOftHeYear doesnt work obviously – Peter Lapisu Sep 23 '14 at 12:38
  • it's an old answer, now it's deprecated, but weekOfYear works, why do you say it doesn't? – meronix Sep 24 '14 at 08:12
1

I'am adding my solution (implemented as an NSDate category), which doesn't use week, which is deprecated in iOS7, iOS8

- (NSDate *)firstDateOfWeek {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *startOfWeek;
    [calendar rangeOfUnit:NSCalendarUnitWeekOfYear startDate:&startOfWeek interval:NULL forDate:self];
    return startOfWeek;
}

- (BOOL)isSameWeekWithDate:(NSDate *)date {
    if (ABS(self.timeIntervalSince1970 - date.timeIntervalSince1970) > (7 * 24 * 60 * 60)) {
        return NO;
    }    
    return ([[self firstDateOfWeek] timeIntervalSince1970] == [[date firstDateOfWeek] timeIntervalSince1970]);
}

- (BOOL)isThisWeek {
    return [self isSameWeekWithDate:[NSDate new]];
}
Peter Lapisu
  • 19,915
  • 16
  • 123
  • 179
0
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSWeekCalendarUnit fromDate:yourDate];
NSInteger week = [components week]; // here your have a Integer with the weeknr of yourDate

components = [cal components:NSWeekCalendarUnit fromDate:[NSDate date]];
weekToday = [components week]; // here your have a Integer with the weeknr of today

The rest you should be able to do. It might get another brainwork when it comes to the last week in year.

Clear?

Jonas Schnelli
  • 9,965
  • 3
  • 48
  • 60
0

NOTE: this calculates the idea of "week" using a Sunday-Saturday concept of week.

To calculate the current day of the week use the following from here:

NSCalendar *gregorian = [[NSCalendar alloc]  initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:dateOfInterest];

NSInteger weekday = [weekdayComponents weekday];
// weekday 1 = Sunday for Gregorian calendar

[gregorian release];

The rest should be pretty trivial. Get the current date and the date from your NSDate. Find the start and end dates using the day and the date (if today is monday then date - 1 day is the first day of the week etc). Figure out which week the date is in.

N_A
  • 19,799
  • 4
  • 52
  • 98
0

For iOS 7 and above, you have to replace NSWeekCalendarUnit with NSCalendarUnitWeekOfYear

- (NSInteger)thisW:(NSDate *)date
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *todaysComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
    NSUInteger todaysWeek = [todaysComponents weekOfYear];
    NSDateComponents *otherComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:date];
    NSUInteger datesWeek = [otherComponents weekOfYear];

    //NSLog(@"Date %@",date);
    if(todaysWeek==datesWeek){
        //NSLog(@"Date is in this week");
        return 1;
    }else if(todaysWeek+1==datesWeek){
        //NSLog(@"Date is in next week");
        return 2;
    } else {
        return 0;
    }

}
Deepak Thakur
  • 3,453
  • 2
  • 37
  • 65
0

Forget about date components, you have to tweak lots of things (check if it's the last week of the year, check if Sunday is the beginning of the week...) and is prone to errors and spaghetti code.

This solves your issue and is extended to detect "last week", "previous weeks", "this week", "next week" and "later weeks"

-(EventWeekRange)numberOfWeeksFromTodayToEvent:(NSDate *)eventDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSComparisonResult comparison = [calendar compareDate:[NSDate date] toDate:eventDate toUnitGranularity:NSCalendarUnitWeekOfYear];
    if (comparison == NSOrderedSame) {
        return RangeThisWeek;
    } else if (comparison == NSOrderedAscending) { // The event date is in the future
        // Advance today's date one week to check if this new date is in the same week as the event
        NSDate *todaysNextWeek = [[NSDate date]dateByAddingTimeInterval:60*60*24*7];
        if ([calendar compareDate:todaysNextWeek toDate:eventDate toUnitGranularity:NSCalendarUnitWeekOfYear] == NSOrderedSame) {
            return RangeNextWeek;
        } else {
            return RangeLater;
        }
    } else { // The event date is in the past
        // Advance the event's date one week to check if this new date is in the same week as today
        NSDate *eventsNextWeek = [eventDate dateByAddingTimeInterval:60*60*24*7];
        if ([calendar compareDate:eventsNextWeek toDate:[NSDate date] toUnitGranularity:NSCalendarUnitWeekOfYear] == NSOrderedSame) {
            return RangeLastWeek;
        } else {
            return RangeEarlier;
        }
    }
}
Riddick
  • 400
  • 2
  • 9