Search code examples
iosobjective-cnsdatenscalendarnsdatecomponents

Objective-C/iOS: Get date for specific day in week (sunday)


I need to get the date of a specific day (Sunday) in the current week. I use this date to determine if some weekly resetting should occur, and I do some calculations on last reset date is before sundays date etc. This has in principal been ask and answered many times, and my solution has worked for the past 6 months. But today, the 29th of December 2013, it stopped working.

The function used at present time:

+ (NSDate *) getSundaysDate{
    NSDate *currentDate  = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setFirstWeekday:1];

    NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSWeekCalendarUnit)  fromDate:currentDate];

    NSDateComponents *dt = [[NSDateComponents alloc]init];
    [dt setWeek:[components week]];
    [dt setWeekday:1];
    [dt setMonth:[components month]];
    [dt setYear:[components year]];

    return [gregorian dateFromComponents:dt];
}

This used to work like a charm, but today, on my apps, this returns:

NSLog(@"sundaysDate %@", [Util getSundaysDate]);
sundaysDate 2012-12-29 23:00:00 +0000
NSLog(@"Current date %@", [[NSDate date] debugDescription]);
Current date 2013-12-29 11:37:23 +0000

Notice the 2012.

I know this has been answered several times, in different contexts, so I apologize in advance, but I simply don't get the 2012.

Edit - just to clarify the functionality needed:

Week starts on Sunday(day 1)

Week ends on Saturday(day 7)

Given current date I need the date of the first day of the week.

Example 1: today is 29th December 2013
Expected: Sunday is 29th December 2013

Example 2: today is 4th January 2014
Expected: Sunday was 29th December 2013

Example 2: today is 8th January 2014
Expected: Sunday was 5th January 2014

Solution

  • I think you need to use WeekOfMonth not Week.
    NSWeekCalendarUnit is essentially week of year so specifying both it and month are in conflict.

    Note that NSWeekCalendarUnit is obsolete:

    Deprecation Statement
    Use weekOfYear or weekOfMonth instead, depending on what you intend.

    NSDate *currentDate  = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setFirstWeekday:1];
    
    NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit)  fromDate:currentDate];
    [components setWeekday:1];
    
    NSDate *sundatsData = [gregorian dateFromComponents: components];
    NSLog(@"sundaysDate: %@", sundatsData);
    

    NSLog output:

    sundaysDate: 2013-12-29 05:00:00 +0000