我想在iPhone上获得周数。我正在使用这段代码
NSNumber* getWeek() {
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"w.ee"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSNumberFormatter *weekNumber = [[NSNumberFormatter alloc] init];
[weekNumber setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *week = [weekNumber numberFromString:dateString];
[weekNumber release];
return week;
}
然而,我有不同的结果,在模拟器上没问题,但是当我在iPhone中运行时这让我“0” IOS 5.0.1
有帮助吗?
答案 0 :(得分:2)
使用字符串表示周数不是获取此类信息的最佳方式。 NSCalendar
和NSDateComponents
专为此类计算而设计:
NSDate *currDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSWeekOfYearCalendarUnit|NSWeekdayCalendarUnit fromDate:currDate];
NSLog(@"%d %d", components.weekOfYear, components.weekday);
您可以在日历调用中指定组件列表(第3行),如示例说明中所示,只保证在NSDateComponents
对象中填充指定的组件。