【发布时间】:2010-07-15 19:12:35
【问题描述】:
假设我们是 2010 年 7 月 15 日,我想获得前一周的第一天,即 7 月 5 日。我有以下方法,但它不起作用。看来我的weekday属性有问题……
+ (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 作为参数,而您似乎可以在其中放入任何内容。
-
其实你可以在里面放任何东西来监听
description消息,一般可以是任何对象,但是NSInteger不是对象:把NSInteger *dayNbr改成NSInteger dayNbr因为你不需要指针,所以将%@更改为%d,因为它是一个整数。 -
谢谢,我没明白 NSInteger 不是对象。
标签: iphone nsdate nsdatecomponents