假設我們是15/07/2010,我想獲得上週的第一天,即7月5日。我有以下方法,但它不起作用。似乎我的週日屬性有問題...NSDate/NSDateComponent問題
+ (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;
}
請問您可以幫忙嗎?
非常感謝,
呂克
首先讓你的類型直線出來,NSLog(@「..%@ ...」,xxx);將採取NSString作爲參數,而你似乎把任何東西都放在裏面。 – mvds 2010-07-15 19:23:46
其實,看起來你可以把任何東西放在裏面聽'description'消息,它通常可以是任何對象,但是'NSInteger'不是一個對象:因爲你不''將'NSInteger * dayNbr'改爲'NSInteger dayNbr' t想要一個指針,並將'%@'更改爲'%d',因爲它是一個整數。 – mvds 2010-07-15 19:34:45
謝謝,我沒有得到NSInteger不是一個對象。 – Luc 2010-07-15 21:04:40