views:

40

answers:

1

Hello,

Let's say we are the 15/07/2010, I would like to get the first day of the previous week, which is the 5 of July. I have the following method but it does not work. Seems that I have a problem with the weekday attribute...

+ (NSDate *)getFirstDayOfPreviousWeek
{
// Get current date
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];

// Get today date at midnight
NSDateComponents *components = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSTimeZoneCalendarUnit) fromDate:now];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
NSInteger *dayNbr = [components weekday];
NSLog(@"week day:%@",dayNbr); // CRASH
NSDate *todayMidnight = [cal dateFromComponents:components];

// Get first day of previous week midnight
components = [[[NSDateComponents alloc] init] autorelease];
NSInteger *wd = [dayNbr intValue] * -1 + 1;
[components setWeekDay:wd];
[components setWeek:-1];
NSDate *newDate = [cal dateByAddingComponents:components toDate:todayMidnight options:0];
[cal release];

NSLog(@"new date:%@", newDate);

return newDate;
}

Could you please help ?

Thanks a lot,

Luc

+1  A: 

I think it should be a lot easier

- (NSDate *)getFirstDayOfPreviousWeek
{
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];
    NSLog(@"Current date: %@", now);

    // required components for today
    NSDateComponents *components = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit ) fromDate:now];

    // adjust them for first day of previous week (Monday)
    [components setWeekday:2];
    [components setWeek:([components week] - 1)];

    // construct new date and return
    NSDate *newDate = [cal dateFromComponents:components];
    NSLog(@"New date: %@", newDate);

    return newDate;
}

Note this solution assumes the first day of the week is Monday.

Nick
Great, thanks a lot.
Luc