Thursday, July 15, 2010

NSDate / NSDateComponent problem

Programmer Question

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



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails