我最近将Xcode更新到版本6.0,当我这样做时,我被警告已弃用NSDateComponents
week
方法,并且新的weekOfYear
方法取代了它。我相信这些方法应该返回1到52年之间的一周序数。但是weekOfYear
带来的价值超过了52。
我用来测试它的代码如下。有人可以帮我核实一下,如果我做错了,请告诉我那是什么?
- (void)testWeekOfYearMethod
{
NSLog(@"Inside testWeekOfYearMethod...");
NSDate *date = [NSDate date];
//NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekCalendarUnit fromDate:date];
NSInteger weekOrdinal = [weekdayComponents weekOfYear];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];
NSString *formattedString = [dateFormatter stringFromDate:date];
NSLog(@"In getWeekContainingDate(), Date: %@ has week %ld", formattedString, [[NSNumber numberWithInteger:weekOrdinal] integerValue]);
}
答案 0 :(得分:4)
weekOfYear
只是访问您创建的NSDateComponents
的相应部分。您的示例未指定选项NSWeekOfYearCalendarUnit
,因此无法访问任何内容!
将其添加到您的选项中,您应该得到您期望的结果:
NSDateComponents *weekdayComponents = [gregorian components:(NSWeekCalendarUnit | NSWeekOfYearCalendarUnit) fromDate:date];